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