-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.js
executable file
·75 lines (70 loc) · 2.06 KB
/
websocket.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
73
74
75
#!/usr/bin/env node
const WebSocket = require('ws');
const https = require('https');
const fs = require('fs');
const allowedFiles = [
"/index.html",
"/index-server.html",
"/js/client.js",
"/js/server.js",
];
function isFileAllowed(file) {
for (let i = 0; i < allowedFiles.length; i++) {
if (allowedFiles[i] === file) {
return true;
}
}
return false;
}
const server = https.createServer({
cert: fs.readFileSync('./cert.pem'),
key: fs.readFileSync('./key.pem')
},
function (req, res) {
if (!isFileAllowed(req.url)) {
res.writeHead(404);
res.end();
return;
}
const content = fs.readFileSync('.' + req.url);
res.writeHead(200, {'Content-Type': req.url.endsWith("html") ? 'text/html' : "text/javascript"});
res.end(content);
}).listen(8443);
const wss = new WebSocket.Server({server});
clients = {};
let clientIdGen = 1;
wss.on('connection', function connection(ws) {
const clientId = clientIdGen++;
clients[clientId] = ws;
console.log("Client %s connected", clientId);
ws.on('close', e => {
console.log("Connection to client %s closed", clientId);
delete clients[clientId];
});
ws.on('message', function incoming(message) {
console.log('received (%s): %s', clientId, message);
let msg;
try {
msg = JSON.parse(message);
} catch (e) {
console.log("Parse error (%s): %s", clientId, e);
return;
}
const fwd = {
from: clientId,
payload: msg.payload
};
if (msg.to === "all") {
for (const rcid in clients) {
if (clients.hasOwnProperty(rcid) && clientId.toString() !== rcid) {
console.log("Relaying to %s", rcid);
clients[rcid].send(JSON.stringify(fwd));
}
}
} else {
console.log("Relaying to %s", msg.to);
clients[msg.to].send(JSON.stringify(fwd));
}
});
});
console.log("Listening...");