Update server.js
Browse files
server.js
CHANGED
|
@@ -3,17 +3,26 @@ const PORT = 7860;
|
|
| 3 |
|
| 4 |
const wss = new WebSocket.Server({ port: PORT });
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
| 12 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
ws.on('close', () => {
|
| 15 |
console.log('Client disconnected');
|
|
|
|
| 16 |
});
|
| 17 |
});
|
| 18 |
|
| 19 |
-
console.log(`WebSocket server
|
|
|
|
| 3 |
|
| 4 |
const wss = new WebSocket.Server({ port: PORT });
|
| 5 |
|
| 6 |
+
// This counter represents number of connected clients
|
| 7 |
+
function broadcastClientCount() {
|
| 8 |
+
const count = wss.clients.size;
|
| 9 |
+
const message = JSON.stringify({ clients: count });
|
| 10 |
|
| 11 |
+
wss.clients.forEach((client) => {
|
| 12 |
+
if (client.readyState === WebSocket.OPEN) {
|
| 13 |
+
client.send(message);
|
| 14 |
+
}
|
| 15 |
});
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
wss.on('connection', (ws) => {
|
| 19 |
+
console.log('Client connected');
|
| 20 |
+
broadcastClientCount(); // On connect
|
| 21 |
|
| 22 |
ws.on('close', () => {
|
| 23 |
console.log('Client disconnected');
|
| 24 |
+
broadcastClientCount(); // On disconnect
|
| 25 |
});
|
| 26 |
});
|
| 27 |
|
| 28 |
+
console.log(`WebSocket server running on ws://localhost:${PORT}`);
|