-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (35 loc) · 1.01 KB
/
server.js
File metadata and controls
43 lines (35 loc) · 1.01 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
const express = require("express");
const { WebSocketServer } = require("ws");
const http = require("http");
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const docs = {};
wss.on("connection", (ws) => {
let currentDocId = null;
ws.on("message", (message) => {
const data = JSON.parse(message);
if (data.type === "join") {
currentDocId = data.docId;
if (docs[currentDocId]) {
ws.send(
JSON.stringify({ type: "update", content: docs[currentDocId] })
);
}
}
if (data.type === "update") {
docs[data.docId] = data.content;
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === 1) {
client.send(
JSON.stringify({ type: "update", content: data.content })
);
}
});
}
});
});
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
console.log(`🚀 WebSocket Server running on port ${PORT}`);
});