-
Notifications
You must be signed in to change notification settings - Fork 0
/
host.js
66 lines (52 loc) · 1.6 KB
/
host.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
let express = require('express');
let simplePeer = require('simple-peer');
let socket = require('socket.io');
let nodeWebrtc = require('wrtc');
let app = express();
const PORT = 4000;
app.use(express.static('public'));
let server = app.listen(PORT, () => {
console.log(`server running on PORT ${PORT}`);
});
let io = socket(server);
let peerConnection = new simplePeer({ wrtc: nodeWebrtc });
//on socket connection opened
io.on('connection', (socket) => {
console.log('New Socket has opened ', socket.id);
//event listeners for socketio
socket.on('offer', sdp => {
/*
host receives offer from visitor and signals it.
*/
peerConnection.signal(sdp);
});
socket.on('disconnection', () => {
//disconnects socket connection
console.log('socket disconnected at node server');
socket.disconnect();
});
//event listeners for simple-peer
peerConnection.on('error', err => console.log('error', err));
peerConnection.on("signal", (data) => {
/*
host prepares answer for the received offer and
sends back to the visitor using socket emit('answer).
*/
const sdp = JSON.stringify(data);
socket.emit('answer', sdp);
});
peerConnection.on('connect', () => {
/*
it gets executed when connection between visitor
and host was successfully established.
*/
console.log('connection established in node');
});
peerConnection.on('data', data => {
console.log('data from visitor: ' + data);
peerConnection.send("responding for " + data);
});
peerConnection.on('close', () => {
console.log('connection has been closed');
});
});