-
Notifications
You must be signed in to change notification settings - Fork 163
/
client.js
50 lines (40 loc) · 1.35 KB
/
client.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
'use strict';
const createExample = require('../../lib/browser/example');
const description = 'This example sends a “ping” from the client \
over an RTCDataChannel. Upon receipt, node-webrtc responds with a \
“pong”. Open the Console to see the pings and pongs…';
function beforeAnswer(peerConnection) {
let dataChannel = null;
let interval = null;
function onMessage({ data }) {
if (data === 'pong') {
console.log('received pong');
}
}
function onDataChannel({ channel }) {
if (channel.label !== 'ping-pong') {
return;
}
dataChannel = channel;
dataChannel.addEventListener('message', onMessage);
interval = setInterval(() => {
console.log('sending ping');
dataChannel.send('ping');
}, 1000);
}
peerConnection.addEventListener('datachannel', onDataChannel);
// NOTE(mroberts): This is a hack so that we can get a callback when the
// RTCPeerConnection is closed. In the future, we can subscribe to
// "connectionstatechange" events.
const { close } = peerConnection;
peerConnection.close = function() {
if (dataChannel) {
dataChannel.removeEventListener('message', onMessage);
}
if (interval) {
clearInterval(interval);
}
return close.apply(this, arguments);
};
}
createExample('ping-pong', description, { beforeAnswer });