Created
May 15, 2021 15:08
-
-
Save oeway/74a889f572516ecf104a6e2c85959f5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<button id="button" onclick="connect()">Connect</button> | |
<div id="div"></div><input id="chat"></input><br> | |
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script> | |
<script> | |
var pc = new RTCPeerConnection(), dc, enterPressed = e => e.keyCode == 13; | |
var connect = () => init(dc = pc.createDataChannel("chat")); | |
pc.ondatachannel = e => init(dc = e.channel); | |
var init = dc => { | |
dc.onopen = e => (dc.send("Hi!"), chat.select()); | |
dc.onclose = e => log("Bye!"); | |
dc.onmessage = e => log(e.data); | |
}; | |
chat.onkeypress = e => { | |
if (!enterPressed(e)) return; | |
dc.send(chat.value); | |
log("> " + chat.value); | |
chat.value = ""; | |
}; | |
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState); | |
pc.onicecandidate = e => send({ candidate: e.candidate }); | |
pc.onnegotiationneeded = e => pc.createOffer() | |
.then(offer => pc.setLocalDescription(offer)) | |
.then(() => send({ sdp: pc.localDescription })) | |
.catch(log); | |
var sc = new BroadcastChannel('my_channel'), send = obj => sc.postMessage(JSON.stringify(obj)); | |
var incoming = msg => msg.sdp && | |
pc.setRemoteDescription(new RTCSessionDescription(msg.sdp)) | |
.then(() => pc.signalingState == "stable" || pc.createAnswer() | |
.then(answer => pc.setLocalDescription(answer)) | |
.then(() => send({ sdp: pc.localDescription }))) | |
.catch(log) || msg.candidate && | |
pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log); | |
sc.onmessage = e => incoming(JSON.parse(e.data)); | |
var log = msg => div.innerHTML += "<br>" + msg; | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment