Update server.js
Browse files
server.js
CHANGED
|
@@ -1,24 +1,27 @@
|
|
| 1 |
-
const
|
| 2 |
|
| 3 |
-
// Create a WebSocket server listening on port
|
| 4 |
-
const
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
});
|
| 17 |
-
});
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
});
|
| 23 |
|
| 24 |
-
console.log(
|
|
|
|
| 1 |
+
const WebSocket = require('ws');
|
| 2 |
|
| 3 |
+
// Create a WebSocket server listening on port 8080
|
| 4 |
+
const wss = new WebSocket.Server({ port: 8080 });
|
| 5 |
|
| 6 |
+
// Event listener for new connections
|
| 7 |
+
wss.on('connection', (ws) => {
|
| 8 |
+
console.log('New client connected');
|
| 9 |
|
| 10 |
+
// Send a message to the client when they connect
|
| 11 |
+
ws.send('Welcome to the WebSocket server!');
|
| 12 |
|
| 13 |
+
// Event listener for messages from the client
|
| 14 |
+
ws.on('message', (message) => {
|
| 15 |
+
console.log(`Received message: ${message}`);
|
| 16 |
+
|
| 17 |
+
// Echo the message back to the client
|
| 18 |
+
ws.send(`You said: ${message}`);
|
| 19 |
});
|
|
|
|
| 20 |
|
| 21 |
+
// Event listener for client disconnects
|
| 22 |
+
ws.on('close', () => {
|
| 23 |
+
console.log('Client disconnected');
|
| 24 |
+
});
|
| 25 |
});
|
| 26 |
|
| 27 |
+
console.log('WebSocket server is running on ws://localhost:8080');
|