forked from heroku-examples/node-ws-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (46 loc) · 1.32 KB
/
index.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
var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000
app.use(express.static(__dirname + '/angular-frontend/app/'));
var server = http.createServer(app)
server.listen(port)
console.log("http server listening on %d", port)
var clients = [ ];
var wss = new WebSocketServer({server: server})
console.log("websocket server created")
wss.on("connection", function(ws) {
var id = clients.push(ws);
console.log(id)
// console.log("websocket connection open")
ws.on("message", function(data) {
console.log(data);
for (var i = 0, len = clients.length; i < len; i++) {
try
{
clients[i].send(data);
}
catch(e)
{
console.log("completeConnection error", e);
console.log(clients.length)
// Additional cleanup required?
}
}
});
ws.on("close", function() {
clients.splice(clients.indexOf(ws), 1);
console.log("websocket connection close")
})
})
wss.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});