You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB
JavaScript

const { WebSocket, WebSocketServer } = require("ws");
const express = require("express");
const PORT = process.env.PORT || 3000;
const index = "index.html";
const server = express()
.use(express.static("public"))
.get("/", (req, res) => {
res.sendFile("index.html", { root: __dirname });
})
.get("/destination", (req, res) => {
res.sendFile("destination.html", { root: __dirname });
})
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const wss = new WebSocketServer({ server, clientTracking: true });
let DESTINATIONS = new Set();
let USERS = new Set();
var theme = "";
const messageProcessor = {
default: (ws, msg) => unknownMsg(msg),
hello: (ws, msg) => registerDest(ws, msg),
drawings: (ws, msg) => toDest(msg),
theme: (ws, msg) => ((theme = msg.theme), broadcast(msg)),
};
const unknownMsg = (msg) => {
console.log("Unknown message type...");
console.log(msg);
};
const registerDest = (ws, msg) => {
console.log("Destination client connected");
DESTINATIONS.add(ws);
ws.on("close", () => {
DESTINATIONS.delete(ws);
});
};
const toDest = (msg) => {
DESTINATIONS.forEach((DESTINATION) => {
if (DESTINATION?.readyState === WebSocket.OPEN) {
DESTINATION.send(JSON.stringify(msg));
}
});
};
const broadcast = (msg) => {
let message = JSON.stringify(msg);
for (const user of USERS.values()) {
if (user?.readyState === WebSocket.OPEN && !DESTINATIONS.has(user)) {
user.send(message);
}
}
};
wss.on("connection", (ws) => {
USERS.add(ws);
ws.send(JSON.stringify({ type: "theme", theme: theme }));
ws.on("message", (data) => {
let message;
try {
message = JSON.parse(data);
} catch (e) {}
if (message) {
(messageProcessor[message.type] || messageProcessor.default)(ws, message);
}
});
ws.on("close", () => {
USERS.delete(ws);
});
});