-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
57 lines (47 loc) · 1.71 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
// create server
const WebSocket = require('ws');
const { randomUUID } = require('crypto');
const PORT = 8080;
const server = new WebSocket.WebSocketServer({ port: PORT });
const activeClients = new Map();
// server got connection request -> now socket object has the specific client bounded
server.on('connection', (socket, req) => {
console.log('coming connection request from ', req.socket.remoteAddress);
const newId = randomUUID();
activeClients.set(socket, newId);
socket.isAlive = true;
socket.on('pong', () => {
// console.log(`client ${activeClients.get(socket)} sends pong!`);
socket.isAlive = true;
});
socket.on('message', (data) => {
console.log(`Client ${newId} sends : ${data}`);
server.clients.forEach((client) => {
if (client != socket && client.readyState == WebSocket.OPEN) {
// send message to that client
client.send(JSON.stringify({ msg: data.toString(), id: newId }));
}
});
});
socket.on('close', () => {
console.log(`client ${activeClients.get(socket)} disconnected`);
activeClients.delete(socket);
});
// on pong set isAlive to true
socket.on('error', (err) => {
console.log(`Error on client ${activeClients.get(socket)}: ${err}`);
});
});
const pingInterval = setInterval(() => {
server.clients.forEach((client) => {
if (client.isAlive == false) {
console.log('Terminating dead connection ', activeClients.get(client));
activeClients.delete(client);
return client.terminate();
}
client.isAlive = false;
client.ping();
});
}, 10000);
server.on('close', () => clearInterval(pingInterval));
console.log('Websocket started at port 8080');