user969068
user969068

Reputation: 2943

webRTC Datachannel is undefined for second peer

I am trying to learn webrtc and its my first attempt, I am trying to create a text based chat using webRTC, after going through a lot of tutorials/tips I tried below code, Now the only issue is I can send/receive text messages between peers using console (window.say in code) but when I try to make it work in HTML forms it only works for the first peer to send messages

here my code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>Live Chat</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
  </head>
  <body>
    <button id="start_chat" name="start_chat">Start Chat</button>
    <textarea rows="20" cols="30" id="chatBox"></textarea>
    <br>
    <input type="text" name="send_text" id="send_text">
    <button id="send_btn" name="send_btn">Send</button>


    <script>
     var dataChannel;
    $(function(){
      var peerConn = new RTCPeerConnection({'iceServers': [{'urls': ['stun:stun.l.google.com:19302']}]});
        function create(which_channel) 
        {
             console.log("Creating ...");
            dataChannel = peerConn.createDataChannel(which_channel);
            dataChannel.onopen = (e) => {
                window.say = (msg) => { dataChannel.send(msg); };
                console.log('Say things with say("hi")');
            };
            dataChannel.onmessage = (e) => {
                    $("#chatBox").append(e.data);
                    console.log('Got message:', e.data); 
                };
            peerConn.createOffer({})
                .then((desc) => peerConn.setLocalDescription(desc))
                .then(() => {})
                .catch((err) => console.error(err));
            peerConn.onicecandidate = (e) => {
                if (e.candidate == null) {
                console.log("Get joiners to call: ", "join(", JSON.stringify(peerConn.localDescription), ")");
                }
            };
        }
        function gotAnswer(answer) {
            console.log("gotAnswer Initializing ...");
            peerConn.setRemoteDescription(new RTCSessionDescription(JSON.parse(answer)));
        };
      function join(offer) {
        console.log("Joining ...");

        peerConn.ondatachannel = (e) => {
        console.log("Joining2 ...");
          var dataChannel = e.channel;
          dataChannel.onopen = (e) => {
            window.say = (msg) => { dataChannel.send(msg); };
            console.log('Say things with say("hi")');
          };
          dataChannel.onmessage = (e) => { 
             $("#chatBox").append(e.data);
             console.log('Got message:', e.data); 
            }
        };

        peerConn.onicecandidate = (e) => {
        console.log("Joining3 ...");
          if (e.candidate == null) {
            console.log("Get the creator to call: gotAnswer(", JSON.stringify(peerConn.localDescription), ")");
          }
        };

        var offerDesc = new RTCSessionDescription(JSON.parse(offer));
        peerConn.setRemoteDescription(offerDesc);
        peerConn.createAnswer({})
          .then((answerDesc) => peerConn.setLocalDescription(answerDesc))
          .catch((err) => console.warn("Couldn't create answer"));
      }

    $("#start_chat").click(function(){
        create("something");
    });
    $("#send_btn").click(function(){
          msg = $("#send_text").val();
          $("#chatBox").append(msg);
          dataChannel.send(msg); 
    });
    });
    </script>
  </body>
</html>

above example is working via console commands, Now When I try to send message using $("#send_btn").click() function, first peer ( which started the session) can send messages.

Second peer get this error when click "#send_btn".

dataChannel is undefined

but second peer can send message using console with say("some message") to first peer.

P.S Do you have any idea how can I implement audio call in this? I want to have a button to make audio call, It shouldn't effect my chat channel, should I open a new peer connection?

Upvotes: 0

Views: 885

Answers (1)

Ajay
Ajay

Reputation: 2643

You are not using the global dataChannel variable for second peer.

function join(offer) {
    console.log("Joining ...");
    peerConn.ondatachannel = (e) => {
      // var dataChannel = e.channel; // here you created new variable in local scope
      dataChannel = e.channel;  // here we are using global scope variable   
      dataChannel.onopen = (e) => {
        window.say = (msg) => { dataChannel.send(msg); };
        console.log('Say things with say("hi")');
      };
      dataChannel.onmessage = (e) => { 
         $("#chatBox").append(e.data);
         console.log('Got message:', e.data); 
        }
    };
    // .....
}

Upvotes: 1

Related Questions