-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
90 lines (86 loc) · 2.11 KB
/
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
var WebSocket = require('ws');
var server = new WebSocket.Server({port: 8765});
var unpairedSocket = null;
//whenever 2 valid connections exist, call pair() on them
server.on('connection', function(socket) {
console.log('connection received');
if (unpairedSocket != null) {
if (unpairedSocket.readyState == WebSocket.CLOSING
|| unpairedSocket.readyState == WebSocket.CLOSED) {
console.log('old connection had close. new connection is waiting to be paired');
unpairedSocket = socket
} else {
console.log('connection paired! No connection is waiting.');
pair(unpairedSocket, socket);
unpairedSocket = null;
}
} else {
console.log('connection is waiting to be paired.');
unpairedSocket = socket;
}
});
//given two active connections, connection them together with RTC
function pair(socketA, socketB) {
//stage 1, ask A for offer.
try {
socketA.send(JSON.stringify({
type: 'SDP_Stage_1'
}));
} catch (e) {
console.log('Could not send SDP_Stage_1');
}
socketA.on('message', function(message) {
message = JSON.parse(message);
switch (message.type) {
case 'offer':
//stage 2, give B A's offer; ask B for answer
try {
socketB.send(JSON.stringify({
type: 'SDP_Stage_2',
data: message.data
}));
} catch (e) {
console.log('Could not send SDP_Stage_2');
}
break;
case 'ice':
//relay all ice messages
try {
socketB.send(JSON.stringify({
type: 'ice',
data: message.data
}));
} catch (e) {
console.log('Could not send ice to B');
}
break;
}
});
socketB.on('message', function(message) {
message = JSON.parse(message);
switch (message.type) {
case 'answer':
//stage 3, give A B's answer.
try {
socketA.send(JSON.stringify({
type: 'SDP_Stage_3',
data: message.data
}));
} catch (e) {
console.log('Could not send SDP_Stage_3');
}
break;
case 'ice':
//relay all ice messages
try {
socketA.send(JSON.stringify({
type: 'ice',
data: message.data
}));
} catch (e) {
console.log('Could not send ice to A');
}
break;
}
});
}