-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (43 loc) · 1.28 KB
/
server.js
File metadata and controls
55 lines (43 loc) · 1.28 KB
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
"use strict";
var http = require("http"),
express = require("express"),
estatic = require("express-static"),
ws = require("ws"),
Server = require("./handlers");
var app = express(),
web = http.createServer(app),
wss = new ws.Server({ server: web });
var sockets = [];
app.use(estatic("static"));
var server = new Server(notify);
wss.on("connection", function(ws) {
var req = ws.upgradeReq, resp = { writeHead: {} };
req.originalUrl = req.url;
ws._eOpened = true;
function removeWS() {
ws.removeAllListeners();
ws._eOpened = false;
sockets.splice(sockets.indexOf(ws), 1);
}
sockets.push(ws);
ws.on("close", removeWS);
ws.on("error", removeWS);
ws.on("message", function(text) {
var msg = JSON.parse(text), type = msg.type;
server.handle(type, msg.data, function(data) {
ws.send(JSON.stringify({ type: type, data: data, id: msg.id }));
}, notify);
});
});
function notify(type, data) {
var pdata = { type: type, data: data }, packed = JSON.stringify(pdata);
sockets.forEach(function(ws) {
if (ws._eOpened)
ws.send(packed);
});
}
// var a = 0;
// setInterval(function() {
// notify("somathig", { cnt: a++ });
// },1000);
web.listen(10000);