Webrtc数据通道始终处于连接状态且未打开

时间:2017-01-20 17:58:01

标签: javascript webrtc

我正在创建一个小的WebRTC应用程序,现在用于交换文本消息。我有WebRTC连接工作,但Datachannel始终保持“连接”状态,永远不会“打开”。

请告诉我这里缺少什么。

以下是JS。

socket.onmessage = function(e){
            console.log("Message from signaling server");
                writeToScreen('<span class="server">Server: </span>'+e.data);
                var data = JSON.parse(e.data);
    switch(data.type) {
    case "login":
    onLogin(data.success);
    break;
    case "offer":
    onOffer(data.offer, data.name);
    break;
    case "answer":
    onAnswer(data.answer);
    break;
    case "candidate":
    onCandidate(data.candidate);
    break;
    default:
    break;
}


            }
            // Enable send and close button
            $('#send').prop('disabled', false);
            $('#close').prop('disabled', false);
            $('#connect').prop('disabled', true);
        }
        function close(){
            socket.close();
        }
        function writeToScreen(msg){
            var screen = $('#screen');
            screen.append('<p>'+msg+'</p>');
            screen.animate({scrollTop: screen.height()}, 10);
        }
        function clearScreen(){
            $('#screen').html('');
        }
        function sendMessage(){
            if(!socket || socket == undefined) return false;
            var mess = $.trim($('#message').val());
            if(mess == '') return;
            writeToScreen('<span class="client">Client: </span>'+mess);
            socket.send(mess);
            // Clear input
            $('#message').val('');
        }
        $(document).ready(function(){
            $('#message').focus();
            $('#frmInput').submit(function(){
                sendMessage();
            });
            $('#connect').click(function(){
                connect();
            });
            $('#close').click(function(){
                close();
            });
            $('#clear').click(function(){
                clearScreen();
            });
        });

        if (!window.RTCPeerConnection) {
    window.RTCPeerConnection = window.webkitRTCPeerConnection;
}

var configuration = {
  "iceServers": [
  {
    "urls": "stun:mmt-stun.verkstad.net"
  },
  {
    "urls": "turn:mmt-turn.verkstad.net",
    "username": "webrtc",
    "credential": "secret"
  }
  ]
};


myConnection = new RTCPeerConnection(configuration,{optional:[{RtpDataChannels: true},{DtlsSrtpKeyAgreement: true}]});

                console.log("RTCPeerConnection object was created");
                console.log(myConnection);  
                openDataChannel();

                //when the browser finds an ice candidate we send it to another peer

                myConnection.onicecandidate = function (event) {
                console.log(event.candidate);
                if (event.candidate) {
                    send({
                    type: "candidate",
                    candidate: event.candidate
                    });
                    }
                };  


// Datachannel

    var mediaConstraints = {
        'offerToReceiveAudio': 1,
        'offerToReceiveVideo': 1
    };


   var connectToOtherUsernameBtn =  document.getElementById("connectToOtherUsernameBtn");   
        console.log(connectToOtherUsernameBtn);

        connectToOtherUsernameBtn.addEventListener("click", function () {
        console.log("ice state : "+myConnection.iceGatheringState);
var otherUsername = connectToOtherUsernameBtn.value;
connectedUser = otherUsername;
        if (otherUsername.length > 0) {
        //make an offer

        myConnection.createOffer(function (offer) {
        send({
        type: "offer",
        offer: offer
        });
        console.log(offer);
        console.log(typeof(offer));
        myConnection.setLocalDescription(offer);
        console.log("localDescription");
        console.log(myConnection.localDescription);
        }, function (error) {
        alert("An error has occurred.");
        console.log(error);
        });
        }
        });


function send(message) {
if (connectedUser) {
message.name = connectedUser;
 }
socket.send(JSON.stringify(message));
};

//when somebody wants to call us
function onOffer(offer, name) {
console.log("offer recieved");
connectedUser = name;
 myConnection.setRemoteDescription(new RTCSessionDescription(offer));
 myConnection.createAnswer(function (answer) {
 myConnection.setLocalDescription(answer);
 send({
 type: "answer",
 answer: answer
 });
 }, function (error) {
 alert("oops...error");
 console.log(error);
 });
  console.log("Answer sent");
}

//when another user answers to our offer
function onAnswer(answer) {
console.log("answer recieved");
myConnection.setRemoteDescription(new RTCSessionDescription(answer));
console.log(myConnection.iceConnectionState );
}
//when we got ice candidate from another user
function onCandidate(candidate) {
myConnection.addIceCandidate(new RTCIceCandidate(candidate));
}


}); 

//data channel

//creating data channel
function openDataChannel() {
console.log("opening Data Channel");
var dataChannelOptions = {
reliable:true,
};
dataChannel = myConnection.createDataChannel("myDataChannel",dataChannelOptions);

 dataChannel.onerror = function (error) {
 console.log("Error:", error);
 };
 dataChannel.onmessage = function (event) {
 console.log("Got message:", event.data);
 };
}



function sendmsg() {
console.log("send message");
var msgInput=document.getElementById("msgInput");
var val = msgInput.value;
console.log(val);
 dataChannel.send(val);
}




function checkstatus(){
console.log("Checking Status");
console.log("signalingState: "+myConnection.signalingState);
console.log("iceConnectionState: "+myConnection.iceConnectionState);
console.log("iceGatheringState: "+myConnection.iceGatheringState);
console.log("localDescription: ");
console.log(myConnection.localDescription);
console.log("remoteDescription:");
console.log(myConnection.remoteDescription);
console.log("Connestion id");
console.log(dataChannel.id);
console.log("Connestion readyState");
console.log(dataChannel.readyState);
}

以下是chrome的控制台日志。 enter image description here

2 个答案:

答案 0 :(得分:2)

删除{RtpDataChannels:true} 再试一次,如果它有效,请烧掉推荐那些&#34; rtp数据通道的教程或书籍。他们坏了。

答案 1 :(得分:2)

我遇到了同样的问题。我的代码在使用localhost信令服务器没有互联网的mozilla上工作正常,但在Chrome上我有这个问题。它的涓流ICE问题。 一个解决方案是你可以设置涓流冰。

在Chrome中,您可能需要通过互联网连接来收集所有可能的ICE候选人。因为在Chrome Datachannel中不会被打开,直到同行获得所有可能的ICE候选人。

您可以尝试以下链接与互联网或没有互联网。你会有简短的想法。 https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/

有关详细信息,请查看此信息 https://webrtcstandards.info/webrtc-trickle-ice/