【问题标题】:webRTC Datachannel is undefined for second peerwebRTC 数据通道未为第二个对等方定义
【发布时间】:2017-05-24 19:30:07
【问题描述】:

我正在尝试学习 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() 函数发送消息时,第一个对等点(启动会话)可以发送消息。

第二个对等点在单击“#send_btn”时收到此错误。

dataChannel is undefined

但是第二个对等点可以使用控制台向第一个对等点发送消息。

P.S 您知道如何在此实现音频通话吗?我想要一个按钮来进行音频通话,它不应该影响我的聊天频道,我应该打开一个新的对等连接吗?

【问题讨论】:

    标签: javascript webrtc


    【解决方案1】:

    您没有将全局 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); 
            }
        };
        // .....
    }
    

    【讨论】:

    • 谢谢您,您知道如何在此实现音频通话吗?我想要一个按钮来进行音频通话,它不应该影响我的聊天频道,我应该打开一个新的数据频道吗?
    • 数据通道仅用于发送/接收数据(文本/blob)。对于音频/视频通话,您需要先将 MediaStream 添加到 PeerConnection,然后再在双方创建提议/答案。见webrtc.github.io/samples & webrtc.github.io/samples/src/content/peerconnection/pc1,
    • 我的错误,我的意思是新的对等连接,我想从文本聊天开始,并在用户点击通话按钮时向他们询问媒体流。我会检查这些链接并更新。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多