]> git.r.bdr.sh - rbdr/junction/blob - server/index.js
Merge branch 'main' of gitlab.com:rbdr/junction into main
[rbdr/junction] / server / index.js
1 const PORT = 8000;
2
3 const express = require('express');
4 const http = require('http');
5 const main = express();
6 const server = http.createServer(main);
7 const io = require('socket.io').listen(server);
8 const events = require('./events');
9
10 server.listen(PORT, null, function() {
11 console.log("Listening on port " + PORT);
12 });
13
14 const sockets = {};
15
16 io.sockets.on('connection', (socket) => {
17 sockets[socket.id] = socket;
18 const me = socket.id;
19
20 console.log(`[CONNECT] New client connected with ID ${me}`);
21
22 socket.on('join', (data) => {
23 Object.entries(io.in(data.url).sockets).forEach(([peerId, peer]) => {
24 if (peerId !== me) {
25 peer.emit(events.types.ADD_PEER, events.addPeer(me, false));
26 socket.emit(events.types.ADD_PEER, events.addPeer(peerId, true));
27 }
28 });
29
30 socket.join(data.url);
31 console.log(`[CONNECT] Client ${me} added to room ${data.url}`);
32 });
33
34 socket.on('disconnecting', () => {
35 const rooms = Object.keys(socket.rooms);
36 rooms.forEach(room => io.to(room).emit(events.types.REMOVE_PEER, events.removePeer(me)));
37
38 console.log(`[DISCONNECT] Client ${me} has disconnected and has been removed from all rooms`);
39 });
40
41 socket.on('relayICECandidate', (data) => {
42 Object.keys(io.in(data.url).sockets).forEach(peer =>
43 peer.emit(events.types.ICE_CANDIDATE_RECEIVED, events.ICECandidateReceived(me, data.ice_candidate)));
44
45 console.log(`[RELAY_ICE_CANDIDATE] ICE candidate for client ${me} has been relayed to all peers`);
46 });
47
48 socket.on('relaySessionDescription', (data) => {
49 Object.keys(io.in(data.url).sockets).forEach(peer =>
50 peer.emit(events.types.SESSION_DESCRIPTION_RECEIVED, events.SessionDescriptionReceived(me, data.session_description)));
51
52 console.log(`[RELAY_SESSION_DESCRIPTION] Session description for client ${me} has been relayed to all peers`);
53 });
54 });