-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_relay.js
More file actions
101 lines (82 loc) · 2.58 KB
/
Copy pathwebsocket_relay.js
File metadata and controls
101 lines (82 loc) · 2.58 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* SPDX-FileCopyrightText: 2024 Volodymyr Shymanskyy
* SPDX-License-Identifier: MIT
*
* The software is provided "as is", without any warranties or guarantees (explicit or implied).
* This includes no assurances about being fit for any specific purpose.
*/
/* npm install ws */
const WebSocket = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({ server });
const rooms = new Map();
wss.on('connection', (ws, req) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const path = url.pathname;
let id, isMainClient;
if (path.startsWith('/new/')) {
id = path.slice(5); // Extract the ID from /new/ID
isMainClient = true;
console.log('New DEV:', id)
} else {
id = path.slice(1); // Extract the ID from /ID
isMainClient = false;
console.log('New IDE:', id)
}
if (!rooms.has(id)) {
rooms.set(id, { main: null, others: new Set() });
}
const room = rooms.get(id);
if (isMainClient) {
// Register the main client
if (room.main) {
ws.close(1000, "ID is already registered");
return;
}
room.main = ws;
ws.on('message', (message, isBinary) => {
//console.log("DEV:", message, isBinary)
// Relay the message to all other rooms
for (const c of room.others) {
if (c.readyState === WebSocket.OPEN) {
c.send(message, { binary: isBinary });
}
}
});
ws.on('close', () => {
room.main = null
// TODO: Disconnect after 30 seconds?
/*for (const c of room.others) {
c.close();
}
rooms.delete(id);*/
});
ws.on('error', () => {
ws.close();
});
} else {
// Register other rooms
if (!room.main) {
ws.close(1000, "Unknown ID");
return;
}
room.others.add(ws);
ws.on('message', (message, isBinary) => {
//console.log("IDE:", message)
// Relay the message to the main client
if (room.main && room.main.readyState === WebSocket.OPEN) {
room.main.send(message, { binary: isBinary });
}
});
ws.on('close', () => {
room.others.delete(ws);
});
ws.on('error', () => {
ws.close();
});
}
});
server.listen(8080, () => {
console.log('WebSocket relay server is listening on port 8080');
});