]> git.r.bdr.sh - rbdr/junction/blame - server/index.js
Format supporting files
[rbdr/junction] / server / index.js
CommitLineData
6a3568bc
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);
6a3568bc 6console.debug(`Listening on port ${port}`);
ed9f8fd5 7
284fc661 8const rooms = {};
ed9f8fd5 9
6a3568bc
RBR
10server.on(events.types.CONNECTION, (socket) => {
11 const me = socket.id;
ed9f8fd5 12
6a3568bc 13 console.debug(`[CONNECT] New client connected with ID ${me}`);
ed9f8fd5 14
6a3568bc
RBR
15 socket.on(events.types.JOIN, async ({ room }) => {
16 socket.join(room);
284fc661 17
6a3568bc
RBR
18 if (!rooms[room]) {
19 rooms[room] = [];
20 }
284fc661 21
6a3568bc 22 rooms[room].push(socket.id);
284fc661 23
6a3568bc
RBR
24 const sockets = await server.in(room).fetchSockets();
25 sockets.forEach((peer) => {
26 if (peer.id !== me) {
27 events.addPeer(me)(peer);
28 events.addPeer(peer.id)(socket);
29 }
ed9f8fd5 30 });
6a3568bc
RBR
31 });
32
33 socket.on(events.types.DISCONNECTING, () => {
34 for (const room in rooms) {
35 if (rooms[room].includes(me)) {
36 rooms[room] = rooms[room].filter((id) => id !== me);
37 events.removePeer(me)(socket.to(room));
38 if (rooms[room].length === 0) {
39 delete rooms[room];
284fc661
RBR
40 }
41 }
6a3568bc
RBR
42 }
43 });
ed9f8fd5 44
6a3568bc
RBR
45 socket.on(events.types.RELAY_ICE_CANDIDATE, async ({ candidate, peerId }) => {
46 events.ICECandidateReceived(me, candidate)(socket.to(peerId));
47 });
ed9f8fd5 48
6a3568bc
RBR
49 socket.on(events.types.RELAY_OFFER, async ({ offer, peerId }) => {
50 events.offerReceived(me, offer)(socket.to(peerId));
51 });
ed9f8fd5 52
6a3568bc
RBR
53 socket.on(events.types.RELAY_ANSWER, async ({ answer, peerId }) => {
54 events.answerReceived(me, answer)(socket.to(peerId));
55 });
80172072 56});