-
Notifications
You must be signed in to change notification settings - Fork 0
/
webSockets.js
69 lines (57 loc) · 1.29 KB
/
webSockets.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
const WebSockets = require('ws')
const sendTo = (socket, data) => {
socket.send(JSON.stringify(data))
}
const broadcast = (clients, data) => {
clients.forEach(client => {
if (client.readyState === WebSockets.OPEN) {
sendTo(client, data)
}
})
}
function heartBeat() {
this.isAlive = true
}
const init = ({ server, app }) => {
const wss = new WebSockets.Server({ server })
app.locals.clientSockets = wss.clients
wss.on('connection', socket => {
socket.isAlive = true
socket.on('pong', heartBeat)
socket.on('message', (data) => {
const { type } = JSON.parse(data)
switch (type) {
case "REQUEST_ADD_NOTE":
sendTo(socket, {
type: "ADD_NOTE"
})
break;
default:
sendTo(socket, {
type: "UNRECOGNIZED MESSAGE TYPE"
})
}
})
sendTo(socket, {
type: "SUCCESSFULLY_CONNECTED"
})
})
const THIRTY_SECONDS = 1000 * 10;
const intId = setInterval(() => {
wss.clients.forEach(client => {
if (!client.isAlive) {
client.terminate()
} else {
client.isAlive = false;
client.ping()
}
})
}, THIRTY_SECONDS)
wss.on('close', (event) => {
clearInterval(intId)
})
}
module.exports = {
init,
broadcast
}