-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
45 lines (35 loc) · 926 Bytes
/
app.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
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port:8000});
var domes = {};
var phones = {};
wss.on('connection', handleConnect);
function genid() {
return Math.floor(Math.random()*0xefff+0x1000).toString(16);
}
function rappend(o, v) {
k = genid();
while (k in o) k = genid;
o[k]=v;
return k;
}
function handleConnect(ws) {
var endpoint = ws.upgradeReq.url;
console.log("Connection to %s endpoint", endpoint);
if (endpoint == "/dome") {
ws.id = rappend(domes, ws);
ws.send(JSON.stringify({"yo":"dome"}));
}
else {
ws.id = rappend(phones, ws);
ws.send(JSON.stringify({"yo":"phone"}));
ws.on('message', function(msg) { handlePhoneMessage(ws, msg); });
}
}
function handlePhoneMessage(ws, msg) {
var parsed = JSON.parse(msg);
console.log("msg from %s: %s", parsed.id, msg);
for (var i in domes) {
try { domes[i].send(msg); }
catch (e) { delete(domes[i]); }
}
}