javascript - 无法设置远程应答 sdp : Called in wrong state: stable

标签 javascript python socket.io webrtc streaming

我正在尝试写一个 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
当两个人联系在一起时,一切都很好。
但是一旦第三个用户尝试连接到他们,流式传输就会停止并出现错误

Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable


我对javascript了解不多,所以我需要你的帮助。谢谢。
附:我在所有浏览器中都看到了这个错误。
查看此存储库
https://github.com/pfertyk/webrtc-working-example
请参阅此说明
https://pfertyk.me/2020/03/webrtc-a-working-example/

最佳答案

您收到此错误消息的原因是,当第三个用户加入时,它会向之前连接的 2 个用户发送要约,因此,它会收到 2 个答案。
由于一个RTCPeerConnection只能建立一个 对等连接,它会在尝试对稍后到达的答案设置远程描述时提示,因为它已经与 SDP 答案最先到达的对等方建立了稳定的连接。
要处理多个用户,您需要实例化一个新的 RTCPeerConnection 对于每个 远程对等。
也就是说,您可以使用某种字典或列表结构来管理多个 RTCPeerConnections。通过您的信令服务器,每当用户连接时,您都可以发出一个唯一的用户 ID(可能是套接字 ID)。收到此 id 时,您只需实例化一个新的 RTCPeerConnection 并将收到的 id 映射到新创建的对等连接,然后您必须在数据结构的所有条目上设置远程描述。
当您覆盖仍在使用的对等连接变量“pc”时,这也将消除每次新用户加入时代码中的内存泄漏。
但请注意,此解决方案根本不可扩展,因为您将成倍地创建新的对等连接,大约 6 时,您的通话质量已经很糟糕了。
如果您打算拥有一间 session 室,您应该考虑使用 SFU ,但请注意,通常设置它非常麻烦。
结帐Janus用于开源 SFU 实现的 videoroom 插件。

关于javascript - 无法设置远程应答 sdp : Called in wrong state: stable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66062565/

相关文章:

python - 1 个 django 应用程序中约有 20 个模型

node.js - Raspberry + socket.io 在本地网络上工作,但不能在外部网络上工作

javascript - 将回调函数结果附加到特定的 div/位置?

javascript - 如何在点击链接时打开产品标签?

python - 如何为年/月/日/小时/分钟/秒的日期时间创建 Pandas 列?

python - 在 plotly 3D 散点图中显示图例和标签轴

javascript - 迭代具有非顺序 id 的 Firebase 子级

javascript - 默认图像未显示在 WP_Customize_Cropped_Image_Control 的定制器中

node.js - `require ' socket.io-client.js '` 不工作

javascript - django 模板中的socket.io - node.js 不服务socket.io.js