This repository was archived by the owner on Feb 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathwebrtc.html
More file actions
63 lines (49 loc) · 2.33 KB
/
Copy pathwebrtc.html
File metadata and controls
63 lines (49 loc) · 2.33 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
58
59
60
61
62
63
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
const STUN_URL = "stun:stun.sipsorcery.com";
const WEBSOCKET_URL = "ws://127.0.0.1:8081/"
var pc, ws;
async function start() {
if (ws != null) await ws.close();
if (pc != null) await pc.close();
pc = new RTCPeerConnection({ iceServers: [{ urls: STUN_URL }] });
pc.ontrack = evt => document.querySelector('#videoCtl').srcObject = evt.streams[0];
pc.onicecandidate = evt => evt.candidate && ws.send(JSON.stringify(evt.candidate));
// Diagnostics.
pc.onicegatheringstatechange = () => console.log("onicegatheringstatechange: " + pc.iceGatheringState);
pc.oniceconnectionstatechange = () => console.log("oniceconnectionstatechange: " + pc.iceConnectionState);
pc.onsignalingstatechange = () => console.log("onsignalingstatechange: " + pc.signalingState);
pc.onconnectionstatechange = () => console.log("onconnectionstatechange: " + pc.connectionState);
ws = new WebSocket(document.querySelector('#websockurl').value, []);
ws.onmessage = async function (evt) {
if (/^[\{"'\s]*candidate/.test(evt.data)) {
pc.addIceCandidate(JSON.parse(evt.data));
}
else {
await pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(evt.data)));
console.log("remote sdp:\n" + pc.remoteDescription.sdp);
pc.createAnswer()
.then((answer) => pc.setLocalDescription(answer))
.then(() => ws.send(JSON.stringify(pc.localDescription)));
}
};
};
async function closePeer() {
await pc.close();
await ws.close();
};
</script>
</head>
<body>
<video controls autoplay="autoplay" id="videoCtl" width="640" height="480"></video>
<div>
<input type="text" id="websockurl" size="40" />
<button type="button" class="btn btn-success" onclick="start();">Start</button>
<button type="button" class="btn btn-success" onclick="closePeer();">Close</button>
</div>
</body>
<script>
document.querySelector('#websockurl').value = WEBSOCKET_URL;
</script>