datachannel stats

by jib1

HTML

Chat: <input id="chat" disabled><div id="div"></div>

JavaScript

const console = {log: msg => div.innerHTML += `${msg}<br>`};
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = e => console.log(pc1.iceConnectionState);

async function dumpStats(pc, header) {
  const dcStats = [...(await pc.getStats()).values()]
      .filter(({type}) => type == "data-channel")
      .map(stat => stat.dataChannelIdentifier);
  console.log(`${header}: ${JSON.stringify(dcStats, null, 2)}`);
}
let channel;

(async () => {
  dumpStats(pc1, "before");
  channel = pc1.createDataChannel("chat");
  console.log(`channel.id = ${channel.id}`);
  channel.onopen = () => {
    console.log("open");
    chat.disabled = false;
  };
  await dumpStats(pc1, "after");
  console.log(`channel.id = ${channel.id}`);
  await pc1.setLocalDescription();
  await dumpStats(pc1, "after SLD");
  console.log(`channel.id = ${channel.id}`);
  await pc2.setRemoteDescription(pc1.localDescription);
  await pc2.setLocalDescription();
  await pc1.setRemoteDescription(pc2.localDescription);
  await dumpStats(pc1, "after stable");
  console.log(`channel.id = ${channel.id}`);
})();

pc2.ondatachannel = ({channel}) => {
  channel.onopen = () => console.log("Chat!");
  channel.onmessage = ({data}) => console.log(`> ${data}`);
};

chat.onkeypress = ({keyCode}) => {
  if (keyCode != 13) return;
  channel.send(chat.value);
  chat.value = "";
};