forked from stevemk14ebr/YTCH
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
76 lines (63 loc) · 1.83 KB
/
server.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const WebSocket = require('ws');
const http = require('http');
const PORT = process.env.PORT || 8080;
const HEARTBEAT_INTERVAL = 3000; // 3 seconds
const CLIENT_TIMEOUT = 6000; // 6 seconds
const server = http.createServer();
const wss = new WebSocket.Server({ server });
const clients = new Set();
function noop() {}
function heartbeat() {
this.isAlive = true;
}
wss.on('connection', (ws) => {
clients.add(ws);
ws.isAlive = true;
console.log('New client connected');
broadcastUserCount();
ws.on('pong', heartbeat);
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
// Broadcast the message to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
} catch (error) {
console.error('Error parsing message:', error);
}
});
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
broadcastUserCount();
});
});
function broadcastUserCount() {
const userCount = clients.size;
const message = JSON.stringify({ type: 'userCount', count: userCount });
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) {
clients.delete(ws);
return ws.terminate();
}
ws.isAlive = false;
ws.ping(noop);
});
broadcastUserCount();
}, HEARTBEAT_INTERVAL);
wss.on('close', () => {
clearInterval(interval);
});
server.listen(PORT, () => {
console.log(`WebSocket server is running on port ${PORT}`);
});