]>
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 | |
8 | const sockets = {}; | |
9 | ||
80172072 | 10 | server.on('connection', (socket) => { |
ed9f8fd5 | 11 | sockets[socket.id] = socket; |
12 | const me = socket.id; | |
13 | ||
14 | console.log(`[CONNECT] New client connected with ID ${me}`); | |
15 | ||
16 | socket.on('join', (data) => { | |
80172072 RBR |
17 | socket.join(data.url); |
18 | const sockets = server.sockets.adapter.rooms.get(data.url); | |
19 | sockets.forEach((peerId) => { | |
c3fafc92 | 20 | if (peerId !== me) { |
80172072 | 21 | const peer = server.sockets.sockets.get(peerId) |
c3fafc92 | 22 | peer.emit(events.types.ADD_PEER, events.addPeer(me, false)); |
23 | socket.emit(events.types.ADD_PEER, events.addPeer(peerId, true)); | |
24 | } | |
ad7fccbe | 25 | }); |
ed9f8fd5 | 26 | console.log(`[CONNECT] Client ${me} added to room ${data.url}`); |
27 | }); | |
28 | ||
29 | socket.on('disconnecting', () => { | |
30 | const rooms = Object.keys(socket.rooms); | |
80172072 | 31 | rooms.forEach(room => server.to(room).emit(events.types.REMOVE_PEER, events.removePeer(me))); |
ed9f8fd5 | 32 | |
33 | console.log(`[DISCONNECT] Client ${me} has disconnected and has been removed from all rooms`); | |
34 | }); | |
35 | ||
36 | socket.on('relayICECandidate', (data) => { | |
80172072 RBR |
37 | const sockets = server.sockets.adapter.rooms.get(data.url); |
38 | sockets.forEach((peerId) => { | |
39 | const peer = server.sockets.sockets.get(peerId) | |
40 | peer.emit(events.types.ICE_CANDIDATE_RECEIVED, events.ICECandidateReceived(me, data.ice_candidate)) | |
41 | }); | |
ed9f8fd5 | 42 | |
43 | console.log(`[RELAY_ICE_CANDIDATE] ICE candidate for client ${me} has been relayed to all peers`); | |
44 | }); | |
45 | ||
46 | socket.on('relaySessionDescription', (data) => { | |
80172072 RBR |
47 | const sockets = server.sockets.adapter.rooms.get(data.url); |
48 | sockets.forEach((peerId) => { | |
49 | const peer = server.sockets.sockets.get(peerId) | |
50 | peer.emit(events.types.SESSION_DESCRIPTION_RECEIVED, events.SessionDescriptionReceived(me, data.session_description)) | |
51 | }); | |
ed9f8fd5 | 52 | |
53 | console.log(`[RELAY_SESSION_DESCRIPTION] Session description for client ${me} has been relayed to all peers`); | |
54 | }); | |
80172072 | 55 | }); |