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', (data
) => {
17 socket
.join(data
.url
);
18 const sockets
= server
.sockets
.adapter
.rooms
.get(data
.url
);
19 sockets
.forEach((peerId
) => {
21 const peer
= server
.sockets
.sockets
.get(peerId
)
22 peer
.emit(events
.types
.ADD_PEER
, events
.addPeer(me
, false));
23 socket
.emit(events
.types
.ADD_PEER
, events
.addPeer(peerId
, 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', (data
) => {
37 const sockets
= server
.sockets
.adapter
.rooms
.get(data
.url
);
38 sockets
.forEach((peerId
) => {
39 const peer
= server
.sockets
.sockets
.get(peerId
)
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', (data
) => {
47 const sockets
= server
.sockets
.adapter
.rooms
.get(data
.url
);
48 sockets
.forEach((peerId
) => {
49 const peer
= server
.sockets
.sockets
.get(peerId
)
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`);