-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
72 lines (60 loc) · 1.74 KB
/
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
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
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/public'));
var server = http.createServer(app);
var wss = new WebSocketServer({server: server});
var connectionIds = {};
wss.on('connection', function connection(ws) {
var remoteIds = Object.keys(connectionIds);
var connectionId;
while(true) {
connectionId = Math.floor(Math.random()*0xffffffff).toString(16);
if (connectionId in connectionIds) {
} else {
connectionIds[connectionId] = true;
break;
}
}
ws.send(JSON.stringify({
messageType: 'connect',
connectionId: connectionId,
remoteIds: remoteIds
}));
wss.clients
.filter(function(client) {return client !== ws;})
.forEach(function(client) {
client.send(JSON.stringify({
messageType: 'connect_remote',
connectionId: connectionId
}));
});
ws.on('message', function incoming(message) {
var data = JSON.stringify({
messageType: 'message',
connectionId: connectionId,
data: JSON.parse(message)
});
wss.clients
.filter(function(client) {return client !== ws;})
.forEach(function(client) {
client.send(data);
});
});
ws.on('close', function() {
delete connectionIds[connectionId];
wss.clients
.filter(function(client) {return client !== ws;})
.forEach(function(client) {
client.send(JSON.stringify({
messageType: 'disconnect_remote',
connectionId: connectionId
}));
});
});
});
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});