-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignal-server.js
98 lines (78 loc) · 2.54 KB
/
signal-server.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
92
93
94
95
96
97
98
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:8080', 'http://messenger-frontend.s3-website-us-east-1.amazonaws.com/']
}
});
const RTCPeerConnection = require('webrtc')
//working stun: stun:3.90.174.173:3478
//turn is running too on same port just need to test
const users = []
app.get('/', (req, res) => {
res.send('<h1>Hey Socket.io</h1>');
});
io.on('connection', (socket) => {
console.log('a user connected');
users.push(socket.id)
console.log("Number of active connections is now:", users.length)
// Create the RTCPeerConnection object
const peerConnection = new RTCPeerConnection({
iceServers: [
{
urls: ['stun:stun.l.google.com:19302']
}
]
})
// Add a listener for the icecandidate event
peerConnection.on('icecandidate', (event) => {
// Signal the ICE candidate to the remote peer
// ...
console.log(event)
})
socket.on('disconnect', () => {
let index = users.indexOf(socket.id);
if (index > -1) {
users.splice(index, 1);
}
console.log('user disconnected');
console.log("Number of active connections is now:", users.length)
});
//returns sessionid to frontend
socket.on('request-sessionid', () => {
io.to(socket.id).emit('return-sessionid', `${socket.id}`);
});
//sends offer to target clients
socket.on("offer", (message) => {
const offer = message.offer;
let targetClient
// Send the offer to the other client
for(let i = 0; i < users.length; i++) {
if(users[i] != socket.id) {
targetClient = users[i]
console.log("target client:", targetClient)
}
}
console.log(socket.id, '=>', targetClient)
console.log(offer)
//This is a temporary solution for testing and will assume there is only one other client who will connect.
io.to(targetClient).emit('offer', offer);
});
//sends WebRTC response back to sender
//this will need to be updated to work with more than one client
socket.on('offer-response', (response) => {
console.log("offer-response:", response.answer)
let sendBackToClient
// Send the response to the other client
for(let i = 0; i < users.length; i++) {
if(users[i] != socket.id) {
sendBackToClient = users[i]
console.log("client response to:", sendBackToClient)
}
}
io.to(sendBackToClient).emit('offer-response', response.answer);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});