-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (66 loc) · 2.31 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import http from "http";
import fs from "fs";
import url from "url";
import LocalStorage from "node-localstorage";
import { WebSocketServer } from "ws";
let start = new Date();
let localStorage = new LocalStorage.LocalStorage('./storage');
const server = http
.createServer(async (req, res) => {
console.log(new Date(), "server.js: ", req.method, req.url);
if (req.url.startsWith("/store_state")) {
const qparams = url.parse(req.url, true).query;
console.log("/store_state", qparams);
//persist.setItem(qparams.user, qparams.lasted_secs);
localStorage.setItem(qparams.user, qparams.lasted_secs);
res.write("\r\n");
res.end();
} else if (req.url.startsWith("/get_state")) {
res.writeHead(200, { "Content-Type": "application/json" });
let kv = {};
for (let i=0;i<localStorage.length;i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
kv = { ...kv, [key]: value };
}
res.write(JSON.stringify(kv));
res.write("\r\n");
res.end();
} else if(req.url.startsWith("/users")) {
res.writeHead(200, { "Content-Type": "application/json" });
let users = [];
for (let i=0; i <localStorage.length; i++) {
users.push(localStorage.key(i));
}
res.write(JSON.stringify(users));
res.write("\r\n");
res.end();
} else {
fs.readFile("index.html", (err, data) => {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
}
})
.listen(3000,
() => console.log("Took " + ( new Date() - start) +" milisseconds to load. Listening on port 3000"));
const wsServer = new WebSocketServer({
path: "/ws",
server: server
});
let sockets = [];
wsServer.on("connection", function (socket) {
console.log("ws connect",socket.address);
sockets.push(socket);
// When you receive a message, send that message to every socket.
socket.on("message", function (msg) {
console.log("ws message", msg.toString());
sockets.forEach(s => { if (socket !== s) s.send(msg);});
});
// When a socket closes, or disconnects, remove it from the array.
socket.on("close", function () {
console.log("ws close");
sockets = sockets.filter (s => s !== socket);
});
});