-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquackfarm.js
40 lines (34 loc) · 839 Bytes
/
quackfarm.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
var WebSocket = require('ws')
function QuackFarm (server) {
this.wss = new WebSocket.Server({ server })
this.sockets = []
this.wss.on('connection', (ws) => {
ws.isAlive = true
this.sockets.push(ws)
ws.send(`welcome to quackfarm! you're quacker #${this.count()}`)
ws.on('pong', () => {
ws.isAlive = true
})
})
setInterval(() => {
this.sockets.forEach((ws) => {
if (!ws.isAlive) {
this.sockets.splice(this.sockets.indexOf(ws), 1)
return ws.terminate()
}
ws.isAlive = false
ws.ping(noop)
})
}, 1000)
}
QuackFarm.prototype.sendQuack = function () {
this.sockets.forEach((ws) => {
if (!ws) return
ws.send('quack!')
})
}
QuackFarm.prototype.count = function () {
return this.sockets.length
}
function noop () {}
module.exports = QuackFarm