DataChannel Example

Example of WebRTC DataChannel

by Hongbo Miao

HTML

<script src="https://webrtc.github.io/adapter/adapter-latest.js">
</script>
<div id='log'>

</div>

JavaScript

"use strict";
let pc1 = new RTCPeerConnection(),
  pc2 = new RTCPeerConnection(),
  div = document.getElementById('log'),
  add = (pc, can) => can && pc.addIceCandidate(can).catch(log),
  log = msg => div.innerHTML += "<br>" + msg,
  exchangeSDP = () => pc1.createOffer().then(d => pc1.setLocalDescription(d))
  .then(() => pc2.setRemoteDescription(pc1.localDescription))
  .then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
  .then(() => pc1.setRemoteDescription(pc2.localDescription))
  .catch(log),
  setChannelEvents = (dataChannel, label) => {
    dataChannel.onerror = log;
    dataChannel.onclose = () => log(`Data Channel is closed: ${label}`);
    dataChannel.onmessage = ev => log(`${label}, Got message:  ${ev.data}`);
    dataChannel.onopen = () => {
      log(`Data Channel is opened: ${label}`)
      console.log('pc1', pc1); //////////////
      console.log('pc2', pc2); //////////////
    };
    setTimeout(() => dataChannel.send('Hello from ' + label), 3000);
  }

setChannelEvents(pc1.createDataChannel('label', {
  reliable: true
}), 'Peer1');
pc2.ondatachannel = evt => setChannelEvents(evt.channel, 'Peer2');
exchangeSDP();