This repository has been archived by the owner on Aug 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathserver.js
90 lines (75 loc) · 1.84 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict';
module.exports = Server => options => {
const { pingInterval = 10000, port = 8443 } = options;
let connectionHandler;
// Start the ws server
const server = new Server({ port });
server.on('connection', ws => {
if (!connectionHandler) {
return;
}
console.log('New connection');
const client = createClient(ws);
connectionHandler(client);
});
function createClient(ws) {
let messageHandler, errorHandler, closeHandler;
// Starts pinging the client every `pingInterval`ms
const stopKeepAlive = startKeepAlive(ws);
ws.on('error', error => {
if (errorHandler) {
errorHandler(error);
}
});
ws.on('close', (code, reason) => {
if (closeHandler) {
closeHandler(code, reason);
stopKeepAlive();
}
});
ws.on('message', message => {
if (messageHandler) {
messageHandler(JSON.parse(message));
}
});
return {
onMessage(handler) {
messageHandler = handler;
},
onError(handler) {
errorHandler = handler;
},
onClose(handler) {
closeHandler = handler;
},
send(message) {
ws.send(JSON.stringify(message));
},
};
}
// Starts pinging a ws connection to make sure it stays alive
function startKeepAlive(ws) {
let isAlive = true;
ws.on('pong', () => {
isAlive = true;
});
// Every `pingInterval` ms, check if socket is still alive and send a new ping
const timer = setInterval(() => {
if (!isAlive) {
ws.terminate();
return;
}
isAlive = false;
ws.ping();
}, pingInterval);
// Return a function that stops the ping timer
return () => {
clearInterval(timer);
};
}
return {
onConnection(handler) {
connectionHandler = handler;
},
};
};