This repository has been archived by the owner on Nov 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 103
/
socketController.js
91 lines (77 loc) · 2.75 KB
/
socketController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// store refs to connected clients' RTC connections
const clientRTCConns = {};
function socketController(server, socketLimit) {
/**
* server: Node Server
* socketLimit: # of socket.io connections to keep
*/
this.io = require('socket.io')(server);
// will store socket connections to Viewers
this.sockets = [];
this.io.on('connection', (socket) => {
console.log('New connection:', socket.id);
// check # of clients
// kick socket off client if full
const checkClientNum = (err, clients) => {
if (err) throw err;
if (clients.length <= socketLimit) {
// keep socket connection
this.sockets.push(socket);
console.log('Added sockets:', this.sockets.map(socket => socket.id));
} else {
socket.emit('full');
}
}
this.io.sockets.clients(checkClientNum);
// variable to bind socketController context in socket handlers
// so that 'this' in socket handlers can access socket
const self = this;
// callee receives offer from new client
socket.on('offer', function (offer) {
// get socket id to send offer to
const calleeSocket = getTargetSocket(self.sockets);
const calleeId = calleeSocket && calleeSocket.id;
// emit to root of client chain
// callee socket's id maintained throughout signaling
if (calleeId) {
// get this socket's id
const callerId = this.id;
console.log('Emitting offer to callee:', calleeId);
socket.to(calleeId).emit('offer', {
callerId: this.id,
offer,
});
}
});
// caller receives answer from callee
socket.on('answer', function (callerId, answer) {
// emit this (callee) socket's id and answer to root of client chain
// callee socket's id maintained throughout signaling
console.log('Emitting answer to caller:', callerId);
socket.to(callerId).emit('answer', {
// MAKE TO: calleeId: this.id,
calleeId: this.id,
answer,
});
});
// send peers in a WebRTC connection new ICE candidates
socket.on('candidate', (peerId, candidate) => {
console.log('Emitting candidate to peer:', peerId);
socket.to(peerId).emit('candidate', candidate);
});
socket.on('disconnect', function() {
console.log(this.id, 'disconnected');
self.sockets = self.sockets.filter(keptSocket => this.id !== keptSocket.id);
console.log('Updated sockets:', self.sockets.map(socket => socket.id));
});
});
}
socketController.prototype.emitNewMagnet = function(magnetURI) {
this.io.emit('magnetURI', magnetURI);
}
// Determines socket of chain to connect to
// TODO: dummy func right now
function getTargetSocket(sockets) {
return sockets[0];
}
module.exports = socketController;