webRTC Datachannel未定义为第二个同行

时间:2017-05-24 19:30:07

标签: javascript webrtc

我正在尝试学习webrtc及其我的第一次尝试,我正在尝试使用webRTC创建基于文本的聊天,经过我尝试下面的代码后的许多教程/提示,现在唯一的问题是我可以发送/使用控制台(代码中的window.say)在对等体之间接收文本消息但是当我尝试使其在HTML表单中工作时,它只适用于第一个对等体发送消息

这里是我的代码:

<!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>

以上示例通过控制台命令工作,现在当我尝试使用$(“#send_btn”)。click()函数发送消息时,第一个peer(启动会话)可以发送消息。

第二个对等点击“#send_btn”时出现此错误。

dataChannel is undefined

但是第二个对等方可以使用控制台发送消息,并说“(某些消息”)给第一个对等方。

P.S你知道我怎么能在这里实现音频通话?我想要一个按钮来拨打音频,它应该不会影响我的聊天频道,我应该打开一个新的对等连接吗?

1 个答案:

答案 0 :(得分:0)

您没有将全局dataChannel变量用于第二个对等方。

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); 
        }
    };
    // .....
}