]> git.r.bdr.sh - rbdr/junction/blame - server/index.js
Use room all around
[rbdr/junction] / server / index.js
CommitLineData
80172072
RBR
1import { Server } from 'socket.io';
2import { port } from './config.js';
3import * as events from './events.js';
ed9f8fd5 4
80172072 5const server = new Server(port);
baea04f1 6console.log(`Listening on port ${port}`);
ed9f8fd5 7
284fc661 8const rooms = {};
ed9f8fd5 9
80172072 10server.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]) {
8a872a93 20 rooms[room] = [];
284fc661
RBR
21 }
22
23 rooms[room].push(socket.id);
24
8a872a93 25 const sockets = await server.in(room).fetchSockets()
284fc661
RBR
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 });
8a872a93 32 console.log(`[CONNECT] Client ${me} added to room ${room}`);
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});