-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
35 lines (29 loc) · 875 Bytes
/
server.js
File metadata and controls
35 lines (29 loc) · 875 Bytes
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
import { WebSocketServer } from "ws";
const PORT = 8080;
const wss = new WebSocketServer({ port: PORT });
const clients = new Map();
let curClientID = 0;
try {
wss.on("connection", function connection(ws) {
ws.on("error", console.error);
ws.on("message", function message(data) {
const senderID = clients.get(ws);
console.log(`Client ${senderID}: ${data}`);
for (const [client, id] of clients) {
if (client !== ws && client.readyState == WebSocket.OPEN) {
client.send(`Client ${id}: ${data}`);
}
}
});
console.log(`Client ${curClientID} connected`);
clients.set(ws, curClientID);
curClientID += 1;
ws.on("close", () => {
clients.delete(ws);
console.log("Client disconnected.");
});
});
console.log("Server opened at port %s", PORT);
} catch (e) {
console.error(e);
}