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
.keys(io
.in(data
.url
).sockets
).forEach(peer
=> {
24 peer
.emit(events
.types
.ADD_PEER
, events
.addPeer(me
, false));
25 socket
.emit(events
.types
.ADD_PEER
, events
.addPeer(peer
, true));
28 socket
.join(data
.url
);
29 console
.log(`[CONNECT] Client ${me} added to room ${data.url}`);
32 socket
.on('disconnecting', () => {
33 const rooms
= Object
.keys(socket
.rooms
);
34 rooms
.forEach(room
=> io
.to(room
).emit(events
.types
.REMOVE_PEER
, events
.removePeer(me
)));
36 console
.log(`[DISCONNECT] Client ${me} has disconnected and has been removed from all rooms`);
39 socket
.on('relayICECandidate', (data
) => {
40 Object
.keys(io
.in(data
.url
).sockets
).forEach(peer
=>
41 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 Object
.keys(io
.in(data
.url
).sockets
).forEach(peer
=>
48 peer
.emit(events
.types
.SESSION_DESCRIPTION_RECEIVED
, events
.SessionDescriptionReceived(me
, data
.session_description
)));
50 console
.log(`[RELAY_SESSION_DESCRIPTION] Session description for client ${me} has been relayed to all peers`);