-
Notifications
You must be signed in to change notification settings - Fork 13
/
server.js
53 lines (43 loc) · 1.13 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
var debug = require('debug')('signalhubws')
module.exports = function (WebSocketClass) {
var wss
var clients = []
var WebSocketServer = WebSocketClass || require('@clusterws/cws').WebSocketServer
function listen (port, cb) {
wss = new WebSocketServer({ port: port })
wss.on('connection', function (ws, req) {
var app = req.url.split('?')[0].split('#')[0].substring(1).split('/')
ws.app = app[app.length - 1]
clients.push(ws)
ws.on('close', () => {
const i = clients.findIndex(c => c === ws)
clients.splice(i, 1)
})
ws.on('message', (data) => {
var jsond
try {
jsond = JSON.parse(data)
} catch (e) {
console.error(e.message)
return
}
debug('Got message', jsond)
clients.forEach((client) => {
if (jsond.app === client.app) {
debug('Broadcasting on app: %s', client.app)
client.send(data)
}
})
})
})
wss.on('listening', function () {
cb()
})
}
return {
listen: listen,
close: (cb) => {
wss.close(cb)
}
}
}