| const WebSocket = require('ws'); |
| const PORT = 7860; |
|
|
| let visits = 0; |
|
|
| const wss = new WebSocket.Server({ port: PORT }); |
|
|
| |
| function broadcastClientCount() { |
| const count = wss.clients.size; |
| const message = JSON.stringify({ online: count, visitor: visits}); |
|
|
| wss.clients.forEach((client) => { |
| if (client.readyState === WebSocket.OPEN) { |
| client.send(message); |
| } |
| }); |
| } |
|
|
| wss.on('connection', (ws) => { |
| visits++; |
| broadcastClientCount(); |
|
|
| ws.on('close', () => { |
| broadcastClientCount(); |
| }); |
| }); |
|
|
| console.log(`WebSocket server running on ws://localhost:${PORT}`); |