WebRTC:强制对等方使用TURN服务器

WebRTC: force peers to use TURN server

本文关键字:方使用 TURN 服务器 对等 WebRTC      更新时间:2023-09-26

我有一个webrtc应用程序,它工作正常,但出于测试目的,我需要测试我的TURN服务器是否有效,但由于两个测试设备都在同一个网络中,我无法测试,认为下面的代码会将候选限制为仅使用TURN服务器的那些,

function onIceCandidate(event, targetSessionID, targetUserName) {
    if (event.candidate) {
    var candidate = event.candidate.candidate;
    if(candidate.indexOf("relay")<0){ // if no relay address is found, assuming it means no TURN server
        return;
    }
    sendMessage(candidate); // using socket.io to send to the otherside
...

但我注意到(非常沮丧),这不起作用,因为当对等方创建答案描述时,

....
a=candidate:0 1 UDP 2128609535 13.198.98.221 58779 typ host
a=candidate:0 2 UDP 2128609534 13.198.98.221 58780 typ host
....

这意味着,通信是直接的,而不是通过TURN服务器,我假设这一点是否正确?现在,如何强制webrtc使用TURN服务器?

我不知道

浏览器是否或何时会支持此功能,但请查看draft-ietf-rtcweb-jsep-08第4.1.1节中的"ICE候选策略",您可以看到将策略设置为"中继"将如何满足您的需求。在当前的 W3C API 草案中,这是使用 RTCIceTransportPolicy 值"relay"为配置中的 iceTranportPolicy 字段设置的。在 https://w3c.github.io/webrtc-pc/中搜索 RTCIceTransportPolicy

中继:ICE 代理仅使用媒体中继候选项,例如通过 TURN 服务器的候选项。

只是添加这个来结束问题,

function onIceCandidate(event, targetSessionID, targetUserName) {
    if (event.candidate) {
    var candidate = event.candidate.candidate;
    if(candidate.indexOf("relay")<0){ // if no relay address is found, assuming it means no TURN server
        return;
    }...

上面的代码有效,检查到wireshark

添加if(candidate.indexOf("relay")<0)条件后,仅通过TURN服务器进行通信,如果服务器不存在/详细信息不正确,则连接状态将受到打击new

编辑:就像卡伦在他的回答中所说的那样,根据 w3 webrtc,传递relay iceTransportPolicy应该可以工作,但我还没有检查它是否在 Firefox 和 Chrome 中实现......

现在,您可以使用 iceTransportPolicy 属性强制转弯

let pc = new RTCPeerConnection({ iceTransportPolicy : "relay" })

https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration/iceTransportPolicy

为了在 Firefox 上进行测试,您可以强制使用 TURN 中继。

在这里查看我的答案!