Created
November 12, 2020 06:38
-
-
Save vsDizzy/7aaea3e521c767d0dbe8471605f32206 to your computer and use it in GitHub Desktop.
WebRTC sample hello world
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
interface Signaller { | |
send(data: unknown): void; | |
onmessage(data: unknown): void; | |
} | |
const ls = { | |
send: (x) => rs.onmessage(x), | |
} as Signaller; | |
const rs = { | |
send: (x) => ls.onmessage(x), | |
} as Signaller; | |
const local = createPc(ls); | |
const remote = createPc(rs); | |
remote.ondatachannel = (dc) => { | |
dc.channel.onmessage = (e) => { | |
console.log(dc.channel.label, e.data); | |
}; | |
}; | |
const dc = local.createDataChannel('txt'); | |
dc.onopen = () => { | |
dc.send('hello'); | |
}; | |
function createPc(signaller: Signaller, cfg = null, polite = true) { | |
const pc = new RTCPeerConnection(cfg); | |
let makingOffer = false; | |
pc.onnegotiationneeded = async () => { | |
try { | |
makingOffer = true; | |
await pc.setLocalDescription(undefined); | |
signaller.send({ description: pc.localDescription }); | |
} finally { | |
makingOffer = false; | |
} | |
}; | |
pc.onicecandidate = ({ candidate }) => { | |
if (candidate) { | |
signaller.send({ candidate }); | |
} | |
}; | |
signaller.onmessage = async ({ | |
description, | |
candidate, | |
}: { | |
description: RTCSessionDescription; | |
candidate: RTCIceCandidate; | |
}) => { | |
let ignoreOffer = false; | |
if (description) { | |
const isOffer = description.type == 'offer'; | |
const offerCollision = | |
isOffer && (makingOffer || pc.signalingState != 'stable'); | |
ignoreOffer = !polite && offerCollision; | |
if (ignoreOffer) { | |
return; | |
} | |
await pc.setRemoteDescription(description); | |
if (isOffer) { | |
await pc.setLocalDescription(undefined); | |
signaller.send({ description: pc.localDescription }); | |
} | |
} else if (candidate) { | |
try { | |
await pc.addIceCandidate(candidate); | |
} catch (err) { | |
if (!ignoreOffer) { | |
throw err; | |
} | |
} | |
} | |
}; | |
return pc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation