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

mid*_*ido 13 javascript webrtc

我有一个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
...
Run Code Online (Sandbox Code Playgroud)

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

....
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
....
Run Code Online (Sandbox Code Playgroud)

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

小智 9

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

let pc = new RTCPeerConnection({ iceTransportPolicy : "relay" })
Run Code Online (Sandbox Code Playgroud)

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


mid*_*ido 6

只是添加这个来关闭问题,

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;
    }...
Run Code Online (Sandbox Code Playgroud)

上面的代码工作,检查wireshark,

添加if(candidate.indexOf("relay")<0)条件后,只能通过TURN服务器进行通信,如果服务器不存在/不正确的详细信息,连接状态会被触发new

编辑:像卡伦在他回答说,根据W3的WebRTC,路过relayiceTransportPolicy应该工作,但是如果在Firefox和Chrome中实现但我没有检查...

  • 马上实施。 (2认同)

Cul*_*ngs 5

我不知道浏览器是否或何时支持该功能,但请看draft-ietf-rtcweb-jsep-08的4.1.1节中的“ ICE候选策略”,您可以看到如何将策略设置为“中继”会做你想要的。在当前的W3C API草案中,使用配置中iceTranports字段的RTCIceTransports值“ relay”进行设置。在https://w3c.github.io/webrtc-pc/中搜索RTCIceTransports