-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatachannel.js
More file actions
57 lines (47 loc) · 1.5 KB
/
Copy pathdatachannel.js
File metadata and controls
57 lines (47 loc) · 1.5 KB
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
"use strict";
const { RTCPeerConnection } = require("..");
async function main() {
const pc1 = new RTCPeerConnection();
const pc2 = new RTCPeerConnection();
let timeout;
const cleanup = () => {
if (timeout) clearTimeout(timeout);
pc1.close();
pc2.close();
};
pc1.addEventListener("icecandidate", ({ candidate }) => {
if (candidate) pc2.addIceCandidate(candidate).catch(console.error);
});
pc2.addEventListener("icecandidate", ({ candidate }) => {
if (candidate) pc1.addIceCandidate(candidate).catch(console.error);
});
pc2.addEventListener("datachannel", ({ channel }) => {
channel.addEventListener("message", ({ data }) => {
console.log(`pc2 received: ${data}`);
channel.send(`echo: ${data}`);
});
});
const channel = pc1.createDataChannel("chat");
channel.addEventListener("open", () => {
channel.send("hello from Node");
});
channel.addEventListener("message", ({ data }) => {
console.log(`pc1 received: ${data}`);
cleanup();
});
const offer = await pc1.createOffer();
await pc1.setLocalDescription(offer);
await pc2.setRemoteDescription(pc1.localDescription);
const answer = await pc2.createAnswer();
await pc2.setLocalDescription(answer);
await pc1.setRemoteDescription(pc2.localDescription);
timeout = setTimeout(() => {
cleanup();
process.exitCode = 1;
console.error("Timed out waiting for data-channel echo");
}, 10000).unref();
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});