JSFiddle - React, Tailwind, and code Playground
JavaScript
const config = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:global.stun.twilio.com:3478?transport=udp' }
]
}
const pc1 = new RTCPeerConnection(config)
const pc2 = new RTCPeerConnection(config)
function waitForIce(conn, desc) {
return new Promise(function (resolve) {
conn.onicecandidate = event => {
if (!event.candidate) {
// We didn't find any more ice candidates
resolve()
}
}
conn.setLocalDescription(desc)
})
}
const channel = pc1.createDataChannel('label')
channel.onopen = function() {
channel.send('hi')
}
pc2.ondatachannel = function (event) {
event.channel.onmessage = function (event) {
document.body.innerHTML += event.data + '<br>'
}
}
async function start() {
// Don't trickle (wait untill it don't find any more icecandidates)
await waitForIce(pc1, await pc1.createOffer())
await pc2.setRemoteDescription(pc1.localDescription)
// Don't trickle (wait untill it don't find any more icecandidates)
await waitForIce(pc2, await pc2.createAnswer())
await pc1.setRemoteDescription(pc2.localDescription)
}
start()