]>
Commit | Line | Data |
---|---|---|
80172072 RBR |
1 | import { Server } from 'socket.io'; |
2 | import { port } from './config.js'; | |
3 | import * as events from './events.js'; | |
ed9f8fd5 | 4 | |
80172072 | 5 | const server = new Server(port); |
baea04f1 | 6 | console.log(`Listening on port ${port}`); |
ed9f8fd5 | 7 | |
284fc661 | 8 | const rooms = {}; |
ed9f8fd5 | 9 | |
80172072 | 10 | server.on('connection', (socket) => { |
ed9f8fd5 | 11 | const me = socket.id; |
12 | ||
13 | console.log(`[CONNECT] New client connected with ID ${me}`); | |
14 | ||
8c7fb565 | 15 | socket.on('join', async (data) => { |
284fc661 RBR |
16 | const room = data.room; |
17 | socket.join(room); | |
18 | ||
19 | if (!rooms[room]) { | |
20 | rooms[room] = {}; | |
21 | } | |
22 | ||
23 | rooms[room].push(socket.id); | |
24 | ||
25 | const sockets = await server.in(data.url).fetchSockets() | |
26 | sockets.forEach((peer) => { | |
27 | if (peer.id !== me) { | |
28 | peer.emit(events.types.ADD_PEER, events.addPeer(me, false)); | |
29 | socket.emit(events.types.ADD_PEER, events.addPeer(peer.id, true)); | |
30 | } | |
31 | }); | |
32 | console.log(`[CONNECT] Client ${me} added to room ${data.url}`); | |
ed9f8fd5 | 33 | }); |
34 | ||
35 | socket.on('disconnecting', () => { | |
ed9f8fd5 | 36 | |
284fc661 RBR |
37 | for (const room in rooms) { |
38 | if (rooms[room].includes(me)) { | |
39 | rooms[room] = rooms[room].filter(id => id !== me); | |
40 | socket.to(room).emit(events.types.REMOVE_PEER, events.removePeer(me)); | |
41 | if (rooms[room].length === 0) { | |
42 | delete rooms[room]; | |
43 | } | |
44 | } | |
45 | } | |
46 | console.log(`[DISCONNECT] Client ${me} has disconnected and has been removed from all rooms`); | |
ed9f8fd5 | 47 | }); |
48 | ||
8c7fb565 | 49 | socket.on('relayICECandidate', async (data) => { |
ed9f8fd5 | 50 | |
284fc661 | 51 | socket.to(data.peerId).emit(events.types.ICE_CANDIDATE_RECEIVED, events.ICECandidateReceived(me, data.candidate)) |
ed9f8fd5 | 52 | console.log(`[RELAY_ICE_CANDIDATE] ICE candidate for client ${me} has been relayed to all peers`); |
53 | }); | |
54 | ||
284fc661 RBR |
55 | socket.on('relayOffer', async (data) => { |
56 | ||
57 | socket.to(data.peerId).emit(events.types.OFFER_RECEIVED, events.offerReceived(me, data.offer)) | |
58 | console.log(`[RELAY_OFFER] ICE offer for client ${me} has been relayed to all peers`); | |
59 | }); | |
60 | ||
61 | socket.on('relayAnswer', async (data) => { | |
ed9f8fd5 | 62 | |
284fc661 RBR |
63 | socket.to(data.peerId).emit(events.types.ANSWER_RECEIVED, events.answerReceived(me, data.answer)) |
64 | console.log(`[RELAY_OFFER] ICE offer for client ${me} has been relayed to all peers`); | |
ed9f8fd5 | 65 | }); |
80172072 | 66 | }); |