File size: 672 Bytes
cdb67ec
 
9e4b649
388cfc7
 
cdb67ec
9e4b649
b516fa4
 
 
388cfc7
9e4b649
b516fa4
 
 
 
cdb67ec
b516fa4
 
 
388cfc7
b516fa4
9e4b649
cdb67ec
b516fa4
cdb67ec
9e4b649
 
b516fa4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const WebSocket = require('ws');
const PORT = 7860;

let visits = 0;

const wss = new WebSocket.Server({ port: PORT });

// This counter represents number of connected clients
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(); // On connect

  ws.on('close', () => {
    broadcastClientCount(); // On disconnect
  });
});

console.log(`WebSocket server running on ws://localhost:${PORT}`);