webrtc中报错Failed to set remote offer sdp

zhangtgv
  • 184

我写的webrtc的demo中, 只要调用setRemoteDescription就会报Failed to set remote offer sdp: Called in wrong state: STATE_SENTINITIATE

这是我前端的代码

<!doctype html>
<html lang="zh-CN">
<head>
        <meta charset="UTF-8">
</head>
<body>
        <video id="video1" autoplay></video>
        <video id="video2" autoplay></video>
</body>
</html>

<script>
    var PeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
    var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
    navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;

    var server = {
        iceServers: [
            {url: "stun:23.21.150.121"},
            {url: "stun:stun.l.google.com:19302"},
            {url: "turn:numb.viagenie.ca", credential: "webrtcdemo", username: "louis%40mozilla.com"}
        ]
    };

    var options = {
        optional: [
            {DtlsSrtpKeyAgreement: true}
        ]
    }

    var socket = new WebSocket('ws://192.168.0.218:9999');

    //var activity = prompt('please input the activity', 'offerer');

    socket.onopen = function(){
        console.log('socket connected');

        navigator.getUserMedia({
                video: true,
                audio: true
        }, function(stream){
                //绑定本地媒体流到video标签用于输出
                document.getElementById('video1').src = URL.createObjectURL(stream);
                //向PeerConnection中加入需要发送的流
                pc.addStream(stream);
                //如果是发送方则发送一个offer信令,否则发送一个answer信令
                pc.createOffer(function(desc){
                    pc.setLocalDescription(desc);
                    socket.send(JSON.stringify({ 
                            event: "sdp",
                            data: {
                                    sdp: desc
                            }
                    }));
                });
        }, function(e) {
                console.log('Reeeejected!', e);
        });
    }

    socket.onmessage = function(event){
        var json = JSON.parse(event.data);
        console.log(json);
        //如果是一个ICE的候选,则将其加入到PeerConnection中,否则设定对方的session描述为传递过来的描述
        if( json.event === "ice_candidate" ){
            if(json.data.candidate){
                pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));
            }
        }else if(json.event === 'sdp'){
            pc.setRemoteDescription(new RTCSessionDescription(json.data.sdp), function(){
                pc.createAnswer(function(desc){
                    pc.setLocalDescription(desc);
                    socket.send(JSON.stringify({ 
                            event: "sdp",
                            data: {
                                    sdp: desc
                            }
                    }));
                }, function(error) {
                        console.log(error);
                        alert(error);
                })
            }, function(error){
                console.log(error);
                alert(error);
            });
        }
    };

    socket.onclose = function(){
        console.log('socket closed');
    }

    // create the PeerConnection
    var pc = new PeerConnection(server, options);

    pc.onicecandidate = function(event){
        socket.send(JSON.stringify({
                event: "ice_candidate",
                data: {
                        candidate: event.candidate
                }
        }));
    };

    //如果检测到媒体流连接到本地,将其绑定到一个video标签上输出
    pc.onaddstream = function(event){
        if(!event){
            return;
        }
        //someVideoElement.src = URL.createObjectURL(event.stream);
        document.getElementById('video2').src = URL.createObjectURL(event.stream);
    };


    // generic error handler
    function errorHandler (err) {
        console.error(err);
    }
</script>

这是我用nodejs写的websocket服务器的代码

(function(){
    var http = require('http');

    var websocketServer = require('websocket').server;
    var server_for_websocket = http.createServer(function(req, res){

    })
    .listen(9999, function(){
        console.log('websocket server start listening at port '+this.address().port);
    });

    var wsServer = new websocketServer({
        httpServer:server_for_websocket
    })

    var clients = {};

    wsServer.on('request', function(request){
        console.log(new Date() + ' connection from origin ' + request.origin);

        var socket_id = create_uid();

        var connection = request.accept(null, request.origin);
        console.log(new Date()+' connection accepted');

        clients[socket_id] = {
            connection : connection,
            socket_id : socket_id
        }

        connection.on('message', function(message){
            if(message.type == 'utf8'){
                var msg_str = message.utf8Data;
                console.log(msg_str);
                broadcast(clients, socket_id, msg_str);
            }
        })
        connection.on('close', function(){
            delete clients[socket_id];
        })
    })
})()

function create_uid(){
    return Date.now()+'_'+Math.floor(Math.random()*100000);
}

function broadcast(clients, my_socket_id, message){
    for(var i in clients){
        if(i != my_socket_id){
            clients[i]['connection'].sendUTF(message);
        }
    }
}
回复
阅读 12.7k
1 个回答
穿拖鞋的怪蜀黍
  • 3
新手上路,请多包涵

DOMException: Failed to set remote answer sdp: Called in wrong state: STATE_INPROGRESS
我遇到这个……

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏