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');
10 server
.listen(PORT
, null, function() {
11 console
.log("Listening on port " + PORT
);
16 io
.sockets
.on('connection', (socket
) => {
17 sockets
[socket
.id
] = socket
;
20 console
.log(`[CONNECT] New client connected with ID ${me}`);
22 socket
.on('join', (data
) => {
23 Object
.entries(io
.in(data
.url
).sockets
).forEach(([peerId
, peer
]) => {
25 peer
.emit(events
.types
.ADD_PEER
, events
.addPeer(me
, false));
26 socket
.emit(events
.types
.ADD_PEER
, events
.addPeer(peerId
, true));
30 socket
.join(data
.url
);
31 console
.log(`[CONNECT] Client ${me} added to room ${data.url}`);
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
)));
38 console
.log(`[DISCONNECT] Client ${me} has disconnected and has been removed from all rooms`);
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
)));
45 console
.log(`[RELAY_ICE_CANDIDATE] ICE candidate for client ${me} has been relayed to all peers`);
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
)));
52 console
.log(`[RELAY_SESSION_DESCRIPTION] Session description for client ${me} has been relayed to all peers`);