-
Notifications
You must be signed in to change notification settings - Fork 0
/
peerProxy.js
63 lines (54 loc) · 1.68 KB
/
peerProxy.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
const { WebSocketServer } = require('ws');
const uuid = require('uuid');
class PeerProxy {
constructor(httpServer) {
// Create a websocket object
const wss = new WebSocketServer({ noServer: true });
// Handle the protocol upgrade from HTTP to WebSocket
httpServer.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
});
// Keep track of all the connections so we can forward messages
let connections = [];
wss.on('connection', (ws) => {
const connection = { id: uuid.v4(), alive: true, ws: ws };
connections.push(connection);
// Forward messages to everyone except the sender
ws.on('message', function message(data) {
connections.forEach((c) => {
if (c.id !== connection.id) {
c.ws.send(data);
}
});
});
// Remove the closed connection so we don't try to forward anymore
ws.on('close', () => {
connections.findIndex((o, i) => {
if (o.id === connection.id) {
connections.splice(i, 1);
return true;
}
});
});
// Respond to pong messages by marking the connection alive
ws.on('pong', () => {
connection.alive = true;
});
});
// Keep active connections alive
setInterval(() => {
connections.forEach((c) => {
// Kill any connection that didn't respond to the ping last time
if (!c.alive) {
c.ws.terminate();
} else {
c.alive = false;
c.ws.ping();
}
});
}, 10000);
}
}
module.exports = { PeerProxy };