-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
91 lines (80 loc) · 1.63 KB
/
index.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
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
import https from 'https';
import fs from 'fs';
import {
WebSocketServer,
} from 'ws';
//
class Room {
constructor({
wss,
}) {
this.wss = wss;
this.sockets = new Set();
}
addSocket(ws) {
this.sockets.add(ws);
ws.on('message', message => {
for (const socket of this.sockets) {
if (socket !== ws) {
console.log('send message', message);
socket.send(message);
}
}
});
ws.on('close', () => {
this.sockets.delete(ws);
});
}
}
//
class Rooms {
constructor({
wss,
}) {
const rooms = new Map();
const sockets = new Set();
wss.on('connection', (ws, req) => {
const roomId = req.url;
let room = rooms.get(roomId);
if (!room) {
room = new Room({
wss,
});
rooms.set(roomId, room);
}
room.addSocket(ws);
});
}
}
//
// websocket server that stupidly proxies messages to all peers
class WebsocketProxy {
constructor({
port,
}) {
this.port = port;
}
async listen() {
const server = https.createServer({
cert: fs.readFileSync('./certs-local/fullchain.pem'),
key: fs.readFileSync('./certs-local/privkey.pem')
});
const wss = new WebSocketServer({
server,
});
const rooms = new Rooms({
wss,
});
await new Promise((accept, reject) => {
server.listen(port, process.env.HOST || '0.0.0.0', () => {
console.log('server listen', port, process.env.HOST);
accept();
});
});
}
}
const port = parseInt(process.env.PORT, 10) || 8001;
const wsp = new WebsocketProxy({
port,
});
wsp.listen();