簡體   English   中英

未為第二個對等方定義webRTC數據通道

[英]webRTC Datachannel is undefined for second peer

在嘗試了下面的代碼之后,我嘗試了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

但是第二個對等方可以使用控制台將帶有say(“ some message”)的消息發送給第一個對等方。

PS:您知道如何在其中進行音頻通話嗎? 我想有一個按鈕來進行音頻通話,這不會影響我的聊天頻道,我應該打開一個新的對等連接嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM