Skip to content

Instantly share code, notes, and snippets.

@vsDizzy
Created November 12, 2020 06:38
Show Gist options
  • Save vsDizzy/7aaea3e521c767d0dbe8471605f32206 to your computer and use it in GitHub Desktop.
Save vsDizzy/7aaea3e521c767d0dbe8471605f32206 to your computer and use it in GitHub Desktop.
WebRTC sample hello world
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