-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.mjs
executable file
·46 lines (36 loc) · 1.13 KB
/
server.mjs
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
#!/usr/local/bin/node
import { WebSocketServer } from "ws";
let port = parseInt(process.env.PORT || "6200");
let verbose = process.env.verbose;
const wss = new WebSocketServer({ port, host: "0.0.0.0" });
let lastTime = Date.now();
wss.on("connection", function connection(ws) {
console.log(`new connection. (${wss.clients.size})`);
ws.on("error", console.error);
ws.on("message", (data) => {
let s = data.toString();
let op = JSON.parse(s);
if (op.action === "sender") {
// mark client as sender
ws.controlSender = true;
console.log("sender declared");
} else if (op.action === "control" || op.action === "button") {
let now = Date.now();
if (verbose === "true") {
console.debug("control time delta:", now - lastTime);
}
lastTime = now;
wss.clients.forEach((client) => {
if (client !== ws && !client.controlSender) {
client.send(s);
}
});
} else {
console.warn("unknown data:", op.action);
}
});
ws.on("close", () => {
console.log(`connection closed. (${wss.clients.size})`);
});
});
console.log("Started at 6200");