-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (58 loc) · 1.85 KB
/
Copy pathserver.js
File metadata and controls
71 lines (58 loc) · 1.85 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
63
64
65
66
67
68
69
70
71
import express from "express";
import { createServer } from "http";
import path from "path";
import { Server } from "socket.io";
const app = express();
const server = createServer(app);
const io = new Server(server);
app.use(express.static(path.join(process.cwd(), "public")));
let remoteItems = {};
io.of("/event").on("connection", (socket) => {
const event_id = socket.handshake.query.event_id;
socket.event_id = event_id;
const guid = socket.event_id;
if (!remoteItems[guid]) {
remoteItems[guid] = { valueBlock: {}, clients: new Set() };
}
remoteItems[guid].clients.add(socket.id);
//send active valueBlock to new client
io.of("/event")
.to(socket.id)
.emit("remoteValue", remoteItems[guid].valueBlock);
socket.on("disconnect", () => {
for (let valueGuid in remoteItems) {
if (
remoteItems.hasOwnProperty(valueGuid) &&
remoteItems[valueGuid]?.clients
) {
if (remoteItems[valueGuid].clients.has(socket.id)) {
remoteItems[valueGuid].clients.delete(socket.id);
if (remoteItems[valueGuid].clients.size === 0) {
delete remoteItems[valueGuid];
}
if (remoteItems[valueGuid]?.host === socket.id) {
remoteItems[valueGuid].value = {};
broadcastMessage(valueGuid, {});
}
break;
}
}
}
});
socket.on("valueBlock", async (data) => {
const { serverData, valueGuid } = data;
remoteItems[valueGuid].valueBlock = serverData;
broadcastMessage(valueGuid, serverData);
});
});
function broadcastMessage(guid, message) {
if (remoteItems?.[guid]?.clients) {
remoteItems[guid].clients.forEach((client) => {
io.of("/event").to(client).emit("remoteValue", message);
});
}
}
const port = process.env.PORT || 8000;
server.listen(port, () => {
console.log("listening on *:" + port);
});