JSFiddle - React, Tailwind, and code Playground

by mickel8

JavaScript

async function run() {
  const pc1 = new RTCPeerConnection();
  const pc2 = new RTCPeerConnection();

  pc1.onconnectionstatechange = (ev) => console.log(`pc1: connection state change: ${pc1.connectionState}`);
  pc1.onnegotiationneeded = () => console.log('pc1: negotiation needed');
  pc1.onicecandidate = (ev) => pc2.addIceCandidate(ev.candidate);
  pc1.ondatachannel = (ev) => {
    // this should never be emitted in our scenario
    console.log(`pc1: a new datachannel, label: ${ev.channel.label}`);
  }

  pc2.onconnectionstatechange = (ev) => console.log(`pc2: connection state change: ${pc1.connectionState}`);
  pc2.onicecandidate = (ev) => pc1.addIceCandidate(ev.candidate);
  pc2.ondatachannel = (ev) => {
    console.log(`pc2: a new datachannel, label: ${ev.channel.label}`);
    ev.channel.onopen = () => {
      console.log(`pc2: channel ${ev.channel.label} ready for writing`);
    }
  }

  const ch1 = pc1.createDataChannel('ch1');
  ch1.onopen = () => console.log(`pc1: channel ${ch1.label} ready for writing`);

  const offer = await pc1.createOffer();
  await pc1.setLocalDescription(offer);
  await pc2.setRemoteDescription(offer);

  const answer = await pc2.createAnswer();
  await pc2.setLocalDescription(answer);
  await pc1.setRemoteDescription(answer);

  setTimeout(function() {
    console.log('Adding channel ch2');
    const ch2 = pc1.createDataChannel('ch2');
    ch2.onopen = () => console.log(`pc1: channel ${ch2.label} ready for writing`);
  }, 2000);
}

run();