首页 > 解决方案 > 无法设置远程应答 sdp:在错误状态下调用:稳定

问题描述

我正在尝试WebRTC使用socket.io.

信令服务器是用 python 编写的,看起来像这样。

import socketio
import uvicorn
from starlette.applications import Starlette

ROOM = 'room'


sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')
star_app = Starlette(debug=True)
app = socketio.ASGIApp(sio, star_app)


@sio.event
async def connect(sid, environ):
    await sio.emit('ready', room=ROOM, skip_sid=sid)
    sio.enter_room(sid, ROOM)


@sio.event
async def data(sid, data):
    await sio.emit('data', data, room=ROOM, skip_sid=sid)


@sio.event
async def disconnect(sid):
    sio.leave_room(sid, ROOM)


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8003)

客户端看起来像这样

<script>
    const SIGNALING_SERVER_URL = 'http://127.0.0.1:8003?session_id=1';
    // WebRTC config: you don't have to change this for the example to work
    // If you are testing on localhost, you can just use PC_CONFIG = {}
    const PC_CONFIG = {};

    // Signaling methods
    let socket = io(SIGNALING_SERVER_URL, {autoConnect: false});

    socket.on('data', (data) => {
        console.log('Data received: ', data);
        handleSignalingData(data);
    });

    socket.on('ready', () => {
        console.log('Ready');
        // Connection with signaling server is ready, and so is local stream
        createPeerConnection();
        sendOffer();
    });

    let sendData = (data) => {
        socket.emit('data', data);
    };

    // WebRTC methods
    let pc;
    let localStream;
    let remoteStreamElement = document.querySelector('#remoteStream');

    let getLocalStream = () => {
        navigator.mediaDevices.getUserMedia({audio: true, video: true})
            .then((stream) => {
                console.log('Stream found');
                localStream = stream;
                // Connect after making sure that local stream is availble
                socket.connect();
            })
            .catch(error => {
                console.error('Stream not found: ', error);
            });
    }

    let createPeerConnection = () => {
        try {
            pc = new RTCPeerConnection(PC_CONFIG);
            pc.onicecandidate = onIceCandidate;
            pc.onaddstream = onAddStream;
            pc.addStream(localStream);
            console.log('PeerConnection created');
        } catch (error) {
            console.error('PeerConnection failed: ', error);
        }
    };

    let sendOffer = () => {
        console.log('Send offer');
        pc.createOffer().then(
            setAndSendLocalDescription,
            (error) => {
                console.error('Send offer failed: ', error);
            }
        );
    };

    let sendAnswer = () => {
        console.log('Send answer');
        pc.createAnswer().then(
            setAndSendLocalDescription,
            (error) => {
                console.error('Send answer failed: ', error);
            }
        );
    };

    let setAndSendLocalDescription = (sessionDescription) => {
        pc.setLocalDescription(sessionDescription);
        console.log('Local description set');
        sendData(sessionDescription);
    };

    let onIceCandidate = (event) => {
        if (event.candidate) {
            console.log('ICE candidate');
            sendData({
                type: 'candidate',
                candidate: event.candidate
            });
        }
    };

    let onAddStream = (event) => {
        console.log('Add stream');
        remoteStreamElement.srcObject = event.stream;
    };

    let handleSignalingData = (data) => {
        // let msg = JSON.parse(data);
        switch (data.type) {
            case 'offer':
                createPeerConnection();
                pc.setRemoteDescription(new RTCSessionDescription(data));
                sendAnswer();
                break;
            case 'answer':
                pc.setRemoteDescription(new RTCSessionDescription(data));
                break;
            case 'candidate':
                pc.addIceCandidate(new RTCIceCandidate(data.candidate));
                break;
        }
    };

    // Start connection
    getLocalStream();
</script>

我也将此代码用于客户端作为socket.io

https://github.com/socketio/socket.io/blob/master/client-dist/socket.io.js

当两个人联系在一起时,一切都很好。 但是一旦第三个用户尝试连接到他们,流式传输就会停止并出现错误

未捕获(承诺中)DOMException:无法在“RTCPeerConnection”上执行“setRemoteDescription”:无法设置远程应答 sdp:在错误状态下调用:稳定

我没有太多的知识javascript,所以我需要你的帮助。谢谢。

PS 我在所有浏览器中都看到了这个错误。

查看此存储库

https://github.com/pfertyk/webrtc-working-example

请参阅此说明

https://pfertyk.me/2020/03/webrtc-a-working-example/

标签: javascriptpythonsocket.iowebrtcstreaming

解决方案


您收到此错误消息的原因是,当第三个用户加入时,它会向之前连接的 2 个用户发送要约,因此会收到 2 个答案。由于一个 RTCPeerConnection 只能建立一个点对点连接,当它尝试对稍后到达的 answer 设置远程描述时会报错,因为它已经与 SDP 回答最先到达的 peer 建立了稳定的连接。要处理多个用户,您需要为每个远程对等方实例化一个新的 RTCPeerConnection。

也就是说,您可以使用某种字典或列表结构来管理多个 RTCPeerConnections。通过您的信令服务器,每当用户连接时,您都可以发出一个唯一的用户 ID(可能是套接字 ID)。当接收到这个 id 时,您只需实例化一个新的 RTCPeerConnection 并将接收到的 id 映射到新创建的对等连接,然后您必须在数据结构的所有条目上设置远程描述。

当您覆盖仍在使用的对等连接变量“pc”时,这也将消除每次新用户加入时代码中的内存泄漏。

但请注意,此解决方案根本不可扩展,因为您将成倍地创建新的对等连接,大约 6 时,您的通话质量已经很糟糕了。如果您打算拥有一个会议室,您应该真正考虑使用SFU,但请注意,通常设置它非常麻烦。

Checkout Janus videoroom 插件,用于开源 SFU 实现。


推荐阅读