]>
Commit | Line | Data |
---|---|---|
1 | import { Server } from 'socket.io'; | |
2 | import { port } from './config.js'; | |
3 | import * as events from './events.js'; | |
4 | ||
5 | const server = new Server(port); | |
6 | console.log(`Listening on port ${port}`); | |
7 | ||
8 | const rooms = {}; | |
9 | ||
10 | server.on('connection', (socket) => { | |
11 | const me = socket.id; | |
12 | ||
13 | console.log(`[CONNECT] New client connected with ID ${me}`); | |
14 | ||
15 | socket.on('join', async (data) => { | |
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(room).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 ${room}`); | |
33 | }); | |
34 | ||
35 | socket.on('disconnecting', () => { | |
36 | ||
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`); | |
47 | }); | |
48 | ||
49 | socket.on('relayICECandidate', async (data) => { | |
50 | ||
51 | socket.to(data.peerId).emit(events.types.ICE_CANDIDATE_RECEIVED, events.ICECandidateReceived(me, data.candidate)) | |
52 | console.log(`[RELAY_ICE_CANDIDATE] ICE candidate for client ${me} has been relayed to all peers`); | |
53 | }); | |
54 | ||
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) => { | |
62 | ||
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`); | |
65 | }); | |
66 | }); |