Skip to content

Commit c23bd55

Browse files
committed
JS Skeleton
1 parent 7d61bde commit c23bd55

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

clients/client.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Import the WebSocket library
2+
const WebSocket = require('ws');
3+
// Import the readline module to read keypresses
4+
const readline = require('readline');
5+
6+
// --- Configuration ---
7+
// Connect to a WebSocket server on the local machine.
8+
// Replace '127.0.0.1' with your server's IP address if it's on your local network.
9+
const SERVER_ADDRESS = 'ws://122.248.228.103/0/ship/JEV';
10+
11+
// --- WebSocket Connection ---
12+
console.log(`Attempting to connect to ${SERVER_ADDRESS}`);
13+
const ws = new WebSocket(SERVER_ADDRESS);
14+
15+
// --- Event Handlers ---
16+
17+
// Handle the connection opening
18+
ws.on('open', function open() {
19+
console.log('Successfully connected to the server!');
20+
console.log('Press "j" for LEFT, "k" for RIGHT, SPACE for FIRE. Press CTRL+C to exit.');
21+
});
22+
23+
// Handle incoming messages from the server
24+
ws.on('message', function incoming(data) {
25+
console.log(`Received from server: ${data}`);
26+
});
27+
28+
// Handle connection errors
29+
ws.on('error', function error(err) {
30+
console.error('Connection Error:', err.message);
31+
console.error('Please make sure the WebSocket server is running.');
32+
process.exit(1); // Exit the program on error
33+
});
34+
35+
// Handle the connection closing
36+
ws.on('close', function close() {
37+
console.log('Disconnected from the server.');
38+
process.exit(0); // Exit the program cleanly
39+
});
40+
41+
// --- Keypress Handling ---
42+
43+
// Set up readline to listen for single keypresses
44+
readline.emitKeypressEvents(process.stdin);
45+
if (process.stdin.isTTY) {
46+
process.stdin.setRawMode(true);
47+
}
48+
49+
// Listen for the 'keypress' event
50+
process.stdin.on('keypress', (str, key) => {
51+
// Exit the program if CTRL+C is pressed
52+
if (key.ctrl && key.name === 'c') {
53+
ws.close();
54+
}
55+
56+
// Check if the connection is open before sending
57+
if (ws.readyState === WebSocket.OPEN) {
58+
let message = '';
59+
60+
if (key.name === 'j') {
61+
message = '{}';
62+
} else if (key.name === 'k') {
63+
message = '{}';
64+
} else if (key.name === 'space') {
65+
message = '{"fire":true}';
66+
}
67+
68+
// If a valid key was pressed, send the message
69+
if (message) {
70+
console.log(`Sending: ${message}`);
71+
ws.send(message);
72+
}
73+
} else {
74+
console.log('WebSocket is not connected. Cannot send message.');
75+
}
76+
});

0 commit comments

Comments
 (0)