1 import { Server
} from 'socket.io';
2 import { port
} from './config.js';
3 import * as events
from './events.js';
5 const server
= new Server(port
);
6 console
.log(`Listening on port ${port}`);
10 server
.on('connection', (socket
) => {
11 sockets
[socket
.id
] = socket
;
14 console
.log(`[CONNECT] New client connected with ID ${me}`);
16 socket
.on('join', async (data
) => {
17 socket
.join(data
.url
);
18 const sockets
= await server
.in(data
.url
).fetchSockets()
20 sockets
.forEach((peer
) => {
22 peer
.emit(events
.types
.ADD_PEER
, events
.addPeer(me
, false));
23 socket
.emit(events
.types
.ADD_PEER
, events
.addPeer(peer
.id
, true));
26 console
.log(`[CONNECT] Client ${me} added to room ${data.url}`);
29 socket
.on('disconnecting', () => {
30 const rooms
= Object
.keys(socket
.rooms
);
31 rooms
.forEach(room
=> server
.to(room
).emit(events
.types
.REMOVE_PEER
, events
.removePeer(me
)));
33 console
.log(`[DISCONNECT] Client ${me} has disconnected and has been removed from all rooms`);
36 socket
.on('relayICECandidate', async (data
) => {
37 const sockets
= await server
.in(data
.url
).fetchSockets()
39 sockets
.forEach((peer
) => {
40 peer
.emit(events
.types
.ICE_CANDIDATE_RECEIVED
, events
.ICECandidateReceived(me
, data
.ice_candidate
))
43 console
.log(`[RELAY_ICE_CANDIDATE] ICE candidate for client ${me} has been relayed to all peers`);
46 socket
.on('relaySessionDescription', async (data
) => {
47 const sockets
= await server
.in(data
.url
).fetchSockets()
49 sockets
.forEach((peer
) => {
50 peer
.emit(events
.types
.SESSION_DESCRIPTION_RECEIVED
, events
.SessionDescriptionReceived(me
, data
.session_description
))
53 console
.log(`[RELAY_SESSION_DESCRIPTION] Session description for client ${me} has been relayed to all peers`);