Search code examples
javascriptwebrtcchannelrtcdatachannelsignaling

A complete example for a WebRTC datachannel with manual signaling


I'm really struggling to get a complete example of a WebRTC datachannel example that I can copy/paste and it works.

I would like a JavaScript example of WebRTC datachannel with manual signaling, i.e., when the example loads, it provides the Signaling data in one text box.

I copy data manually (highlight, copy) and paste it in the peer's window which has a text box to accept that signaling data. I believe there needs to be an "answer" in the signaling data, so there need to be corresponding text boxes waiting for that input as well.

Could the example use Google's free STUN server, please?

I get really confused with bit by bit examples. I want one file, please, that contains the HTML and JavaScript (no CSS or jQuery, please). It is enough for the code to work on Chrome only.


Solution

  • Here it is. Click the blue button below in two different tabs/windows/browsers/machines:

    const output = document.getElementById('output');
    const config = {
      iceServers: [{
        urls: "stun:stun.l.google.com:19302" // list of free STUN servers: https://gist.github.com/zziuni/3741933
      }]
    };
    const pc = new RTCPeerConnection(config);
    const dc = pc.createDataChannel("chat", {
      negotiated: true,
      id: 0
    });
    const log = msg => output.innerHTML += `<br>${msg}`;
    dc.onopen = () => chat.select();
    dc.onmessage = e => log(`> ${e.data}`);
    pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);
    
    chat.onkeypress = function(e) {
      if (e.keyCode != 13) return;
      dc.send(chat.value);
      log(chat.value);
      chat.value = "";
    };
    
    async function createOffer() {
      button.disabled = true;
      await pc.setLocalDescription(await pc.createOffer());
      pc.onicecandidate = ({
        candidate
      }) => {
        if (candidate) return;
        offer.value = pc.localDescription.sdp;
        offer.select();
        answer.placeholder = "Paste answer here. And Press Enter";
      };
    }
    
    offer.onkeypress = async function(e) {
      if (e.keyCode != 13 || pc.signalingState != "stable") return;
      button.disabled = offer.disabled = true;
      await pc.setRemoteDescription({
        type: "offer",
        sdp: offer.value
      });
      await pc.setLocalDescription(await pc.createAnswer());
      pc.onicecandidate = ({
        candidate
      }) => {
        if (candidate) return;
        answer.focus();
        answer.value = pc.localDescription.sdp;
        answer.select();
      };
    };
    
    answer.onkeypress = function(e) {
      if (e.keyCode != 13 || pc.signalingState != "have-local-offer") return;
      answer.disabled = true;
      pc.setRemoteDescription({
        type: "answer",
        sdp: answer.value
      });
    };
    
    pc.onconnectionstatechange = ev => handleChange();
    pc.oniceconnectionstatechange = ev => handleChange();
    
    function handleChange() {
      let stat = 'ConnectionState: <strong>' + pc.connectionState + '</strong> IceConnectionState: <strong>' + pc.iceConnectionState + '</strong>';
      document.getElementById('stat').innerHTML = stat;
      console.log('%c' + new Date().toISOString() + ': ConnectionState: %c' + pc.connectionState + ' %cIceConnectionState: %c' + pc.iceConnectionState,
        'color:yellow', 'color:orange', 'color:yellow', 'color:orange');
    }
    handleChange();
    <p id=stat></p>
    <button id="button" onclick="createOffer()">Offer:</button>
    <textarea id="offer" placeholder="Paste offer here. And press Enter"></textarea> Answer: <textarea id="answer"></textarea><br> Chat: <input id="chat"><br>
    <pre id="output">Chat: </pre>

    Then follow these steps:

    1. In Window A, press the Offer button and copy the offer to the clipboard.
    2. In Window B, paste that offer into "Paste offer here" and hit the Enter key.
    3. Copy the answer that appears after a few seconds.
    4. Return to window A and paste that answer where it says "Paste answer here" and hit Enter.

    You should now see a message saying you're "connected". Type in the chat box to chat!

    If you and a friend exchange the offer/answer somehow, you now have a direct peer-to-peer connection. This should work around the world (modulo symmetric NAT routers); no data server involved.