当包含 ice 服务器时,WebRTC 卡在连接状态(远程候选甚至通过 LAN 引起问题)

WebRTC stuck in connecting state when ice servers are included (remote candidates causing issues even over LAN)

我在尝试解决 .

时临时创建了一个没有任何 iceServersRTCPeerConnection
let peer = new RTCPeerConnection();

这在我的本地网络上一直运行良好。

但是,不在同一网络上的设备(例如,4G 手机)无法连接。我记得我必须向 RTCPeerConnection 构造函数添加一些 iceServers

let peer = RTCPeerConnection(
  {
    iceServers: [
      {
        urls: [
          "stun:stun1.l.google.com:19302",
          "stun:stun2.l.google.com:19302",
        ],
      },
      {
        urls: [
          "stun:global.stun.twilio.com:3478?transport=udp",
        ],
      },
    ],
    iceCandidatePoolSize: 10,
  }
);

这样做之后,我的WebRTC连接就一直卡在连接状态。即使在我的本地网络上,也没有一个连接成功。 (不再是这种情况,请参阅下面的 edit 2

这是连接状态:


编辑:看起来比当我将 iceServers 留空时,连接仍然收集冰候选者,所以我假设我的浏览器(chrome) 提供了一个默认的 ice 服务器。在那种情况下,只有我的自定义 ice 服务器(如上所示)导致了问题,而不是浏览器默认设置。


编辑 2:新观察

我已经添加了大量的日志记录,而且每当我确实包含 iceServers 时,我都会注意到一些事情:

每当对等点 A 在一段时间内第一次发起与对等点 B 的连接时,对等点 B 会收集两个 ice 候选者:1 个本地主机候选者和 1 个远程候选者。如上所述,连接失败。

但是当我快速尝试再次连接时...对等点 B 只收集了一个 ice 候选者:本地主机候选者。不聚集远程候选人。我的第一个假设是我正在使用的 STUN 服务器(在本例中可能是 google's)对其服务有某种形式的速率限制。这个场景真正有趣的是,连接成功了!!

远程候选人搞乱连接有些神秘...我希望这些新细节能有所帮助。我被困在这几个月了!而且这两个设备都在我的局域网上,所以我希望远程候选人完全没有影响。


Peer A代码(发起者):

export class WebRTCConnection {
  private _RTCPeerConnection: any;
  private _fetch: any;
  private _crypto: any;

  private _entity: any;
  private _hostAddress: any;
  private _eventHandlers: ConnectionEventHandlers;
  private _peer: any;
  private _peerChannel: any;

  constructor({
    entity,
    hostAddress,
    eventHandlers,
    RTCPeerConnection,
    fetch,
    crypto,
  }: {
    entity: any,
    hostAddress: any,
    eventHandlers: ConnectionEventHandlers,
    RTCPeerConnection: any,
    fetch: any,
    crypto: any,
  }) {
    this._RTCPeerConnection = RTCPeerConnection;
    this._fetch = fetch;
    this._crypto = crypto;

    this._entity = entity;
    this._hostAddress = hostAddress;
    this._eventHandlers = eventHandlers;

    this._initPeer();
  }

  async _initPeer() {
    this._peer = new this._RTCPeerConnection(/* as shown in question */);

    let resolveOfferPromise: (value: any) => void;
    let resolveIceCandidatesPromise: (value: any[]) => void;
    
    let iceCandidatesPromise: Promise<any[]> = new Promise((resolve, _reject) => {
      resolveIceCandidatesPromise = resolve;
    });

    let offerPromise: Promise<any> = new Promise((resolve, _reject) => {
      resolveOfferPromise = resolve;
    });

    this._peer.onnegotiationneeded = async () => {
      let offer = await this._peer.createOffer();
      await this._peer.setLocalDescription(offer);
      resolveOfferPromise(this._peer.localDescription);
    };

    this._peer.onicecandidateerror = () => {
      // log error
    };

    let iceCandidates: any[] = [];

    this._peer.onicecandidate = async (evt: any) => {
      if (evt.candidate) {
        // Save ice candidate
        iceCandidates.push(evt.candidate);
      } else {
        resolveIceCandidatesPromise(iceCandidates);
      }
    };

    (async () => {
      // No more ice candidates, send on over signaling service
      let offer: any = await offerPromise;
      let iceCandidates: any[] = await iceCandidatesPromise;

      let sigData = // reponse after sending offer and iceCandidates over signaling service

      let answer = sigData.answer;
      await this._peer.setRemoteDescription(answer);

      for (let candidate of sigData.iceCandidates) {
        await this._peer.addIceCandidate(candidate);
      }
    })();

    this._peer.onicegatheringstatechange = (evt: any) => {
      // log state
    };

    this._peer.onconnectionstatechange = async () => {
      // log state
    };

    this._peerChannel = this._peer.createDataChannel("...", {
      id: ...,
      ordered: true,
    });

    this._peerChannel.onopen = () => {
      // log this
    };

    this._peerChannel.onmessage = (event: any) => {
      // do something
    };
  }

  send(msg: any) {
    this._peerChannel.send(
      new TextEncoder().encode(JSON.stringify(msg)).buffer,
    );
  }

  close() {
    if (this._peer) {
      this._peer.destroy();
    }
  }
}

同行B代码:

export class WebRTCConnection {
  constructor({ signalData, eventHandlers, RTCPeerConnection }) {
    this._eventHandlers = eventHandlers;

    this._peer = new RTCPeerConnection(/* as seen above */);

    this._isChannelOpen = false;

    this._peer.ondatachannel = (event) => {
      event.channel.onopen = () => {
        this._mainDataChannel = event.channel;
        event.channel.onmessage = async (event) => {
          // do something
        };
        this._isChannelOpen = true;
      };
    };

    this._peer.onicecandidateerror = () => {
      // log error
    };

    this._iceCandidates = [];
    this._isIceCandidatesFinished = false;
    this._iceCandidatesPromise = new Promise((resolve, _reject) => {
      this._resolveIceCandidatesPromise = resolve;
    });
    this._isAnswerFinished = false;
    this._isSignalDataSent = false;

    this._peer.onicecandidate = async (evt) => {
      if (evt.candidate) {
        // Save ice candidate
        this._iceCandidates.push(evt.candidate);
      } else {
        // No more ice candidates, send on over signaling service when ready
        this._isIceCandidatesFinished = true;
        this._resolveIceCandidatesPromise();
        this._sendSignalData();
      }
    };

    (async () => {
      let sigData = JSON.parse(signalData);

      let offer = sigData.offer;
      await this._peer.setRemoteDescription(offer);

      this._answer = await this._peer.createAnswer();
      await this._peer.setLocalDescription(this._answer);

      for (let candidate of sigData.iceCandidates) {
        await this._peer.addIceCandidate(candidate);
      }

      this._isAnswerFinished = true;
      this._sendSignalData();
    })();

    this._peer.onconnectionstatechange = async () => {
      // log state
    };
  }

  _sendSignalData() {
    if (false
      || !this._isIceCandidatesFinished
      || !this._isAnswerFinished
      || this._isSignalDataSent
    ) {
      return;
    }

    this._isSignalDataSent = true;

    this._eventHandlers.onSignal(JSON.stringify({
      answer: {
        type: this._answer.type,
        sdp: this._answer.sdp,
      },
      iceCandidates: this._iceCandidates,
    }));
  }

  send(msg) {
    this._mainDataChannel.send(new TextEncoder().encode(JSON.stringify(msg)));
  }

  close() {
    this._peer.destroy();
  }
}

您的代码无需 iceServers 即可在 LAN 上运行,因为 STUN 服务器不用于收集候选主机——您的计算机已经知道其本地 IP 地址——并且候选主机足以在 LAN 上建立 WebRTC 连接。

连接可能失败,因为其中一个对等方位于 symmetric NAT, over which STUN fails to work. You can check whether the network is behind a symmetric NAT by using the code in this page: Am I behind a Symmetric NAT? (This page also provide a JSFiddle 之后,您可以在其中检查控制台消息是否打印“normal nat”或“symmetric nat”。如果它什么都不打印,而 fiddle 正常工作,则意味着您没有获得服务器自反候选者。)

我认为您应该首先在 WAN 上测试您的代码,并与被检查是否支持正常 nat 的同行一起测试。您是否曾经在 WAN 上尝试过通过以太网或 WiFi 连接的两个对等体的代码?好像3G/4G网络经常在对称NAT下。

UPDATE(感谢 @Sean DuBois for the ): A "symmetric NAT", an expression I used above and was introduced in RFC 3489 (March 2003), can be better termed by the updated terminology introduced in RFC 4787 (January 2007). STUN 仅适用于具有“端点独立映射”行为的 NAT。 “对称 NAT”(旧术语)具有“Address-Dependent Mapping”行为或“Address and Port-依赖映射”行为,不是端点独立映射”行为。

问题是我使用的是 Brave 浏览器。

使用 Chrome 解决了所有问题。