-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (52 loc) · 1.75 KB
/
Copy pathserver.js
File metadata and controls
62 lines (52 loc) · 1.75 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
56
57
58
59
60
61
62
// express implements a high-level webserver api
const express = require("express");
// create webserver instance
const app = express();
const port = 8080;
// serve the web-app files
app.use(express.static("web-app/dist"));
// attach the websocket server
const ws = require('express-ws')(app, undefined, { clientTracking: true });
// encode and wrap message in metadata
function encapsulate(from, message) {
let payload = {
server: false,
message: Buffer.from(message, 'binary').toString('base64'),
};
if (from === null) payload[server] = true;
return JSON.stringify(payload);
}
// send a message to all clients in a particular room
// except the sender
function broadcast(from, roomID, payload) {
// iterate over all the clients
ws.getWss().clients.forEach(function each(client) {
// if client is not sender and can receive messages
if (client !== from && client.readyState === 1) {
// if client is in this room
if (client.protocol === roomID) {
client.send(encapsulate(from, payload));
}
}
});
}
// WebSocket connection handling
app.ws("/", function connection(s, req) {
// grab the room id from the request
let roomID = req.headers["sec-websocket-protocol"];
//let roomID = new URL(req.url).searchParams.get("room");
// check that the roomid is valid
let r = /^[A-Fa-f0-9]{64}$/;
if (!r.test(roomID)) {
s.close(0, "error: invalid room key");
return;
}
// attach an incoming message handler
s.on("message", function message(m) {
broadcast(s, roomID, m);
});
// broadcast a joined message
broadcast(null, roomID, "new client joined the room");
});
// start listening
app.listen(port);