-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
57 lines (57 loc) · 1.9 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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const WebSocket = require("ws");
// define count to give out different client ids
let clientIdCounter = 0;
// get port from shell or set default (8000)
const port = Number(process.env.PORT) || 8000;
// create WebSocket server
const server = new WebSocket.Server({ port: port });
// list of client messages
const messageList = [];
// list of connected sockets
const clientSockets = new Set();
server.on("connection", (socket) => {
clientSockets.add(socket);
const initMessageObj = {
id: ++clientIdCounter,
messages: messageList,
};
const initCarrierMessage = {
selector: "init",
data: JSON.stringify(initMessageObj),
};
socket.send(JSON.stringify(initCarrierMessage));
socket.on("message", (message) => {
const carrierMessage = JSON.parse(message);
const selector = carrierMessage.selector;
const data = carrierMessage.data;
switch (selector) {
case "text-message": {
const textMessage = JSON.parse(data);
// add message to message list
messageList.push(textMessage);
console.log(`#${textMessage.client}: "${textMessage.text}"`);
// broadcast message to all connected clients
for (let socket of clientSockets) {
socket.send(message);
}
break;
}
case "clear": {
messageList.length = 0;
// send clear message to all connected clients
for (let socket of clientSockets) {
socket.send(message);
}
break;
}
default:
break;
}
});
socket.on("close", () => {
clientSockets.delete(socket);
});
});
//# sourceMappingURL=server.js.map