WebRTC localConnection.setRemoteDescription(answer) 等待时间过长

WebRTC localConnection.setRemoteDescription(answer) pending for too long

我正在尝试在我的浏览器(点 1)和不同网络上的另一个浏览器(点 2)之间实现一个简单的消息传递机制。我正在使用 Google 的 public STUN 服务器进行学习。

节点 1 首先执行以下操作:

const iceConfiguration = {
    iceServers: [
        {
            urls: [
                'stun:stun.stunprotocol.org',
                'stun:stun.sipgate.net:10000',
            ],
        },
    ]
}

const lc = new RTCPeerConnection(iceConfiguration)

const dc = lc.createDataChannel("channel");

dc.onmessage = e => console.log("Just got a message: " + e.data);
dc.onopen = e => console.log("Connection opened.")
lc.onicecandidate = e => console.log("New Ice Candidate! Reprinting SDP" + JSON.stringify(lc.localDescription))

lc.createOffer().then(o => lc.setLocalDescription(o)).then(a => console.log("Set successfully."))

然后,我复制生成的 SDP 并将其发送到对等点 2,然后对等点 2 执行以下操作:

/*
    REMOTE_OFFER_OBJECT is the SDP generated by peer 1
*/
const offer = REMOTE_OFFER_OBJECT

const iceConfiguration = {
    iceServers: [
        {
            urls: [
                'stun:stun.stunprotocol.org',
                'stun:stun.sipgate.net:10000',
            ],
        },
    ]
}

const rc = new RTCPeerConnection(iceConfiguration);

rc.onicecandidate = e => console.log("New Ice Candidate! Reprinting SDP" + JSON.stringify(rc.localDescription))

rc.ondatachannel = e => {
    rc.dc = e.channel;
    rc.dc.onmessage = e => console.log("New message: ", e.data)
    rc.dc.onopen = e => console.log("Connection opened.")
}

rc.setRemoteDescription(offer).then(a => console.log("Offer set."))

rc.createAnswer().then(a => rc.setLocalDescription(a)).then(a => console.log("Answer created."))

对等点 2 复制其生成的 SDP 并将其发送到对等点 1,然后尝试设置其远程描述:

const answer = REMOTE_ANSWER_OBJECT

lc.setRemoteDescription(answer)

最后一条语句挂起的时间太长,没有停止。如果对等点 2 在我的同一网络上,它会正常工作。我可能将 STUN 服务器设置错误,或者 public Google STUN 服务器可能不是一个好主意。此外,createOffer() 和 createAnswer() 调用会生成多个 SDP,但我只复制并发送最后一个。 如何在 WebRTC 中与不同网络上的某个人正确设置对等 2 对等连接?我希望有一个免费的 STUN 服务器的解决方案,因为我目前只是为了学习。

这是您要完成的任务的完整示例。请注意,它还有一个 Google STUN 服务器的代码,但被注释掉了:https://owebio.github.io/serverless-webrtc-chat/.

该页面使用了两个 iframe:

创建:https://owebio.github.io/serverless-webrtc-chat/noserv.create.html

加入:https://owebio.github.io/serverless-webrtc-chat/noserv.join.html.

这应该可以帮助您入门。

此外,还有两个构建在 WebTorrent 上的库可以帮助仅使用浏览器发现和连接到对等点:Bugout, P2PT

就我而言,需要 TURN 服务器。这就是为什么不能将答案设置为远程描述的原因,因为提供者无法找到到回答者的路径。 TURN 服务器很可能会花钱,除非我在 Docker.

上使用 Coturn 图像配置自己的服务器