You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取RTCDatachannel当前的连接类型:host/srflx/prflx/relay?

获取RTCDatachannel实际连接的ICE候选类型

要拿到当前实际使用的连接类型(host/srflx/prflx/relay),解析SDP的方式不可行——SDP仅包含协商阶段收集到的所有候选,并非最终选中的生效连接。你需要通过RTCPeerConnection的getStats() API获取实时统计数据,从中提取实际使用的候选类型。

具体操作步骤:

  • 调用peerConnection.getStats(),该方法返回Promise,解析后得到RTCStatsReport对象。
  • 遍历统计条目,找到类型为iceCandidatePair且state为succeeded的条目,这代表已成功建立的连接候选对。
  • 通过候选对的localCandidateId和remoteCandidateId,从统计报告中获取对应候选的详情,其中type字段即为目标连接类型。

示例代码:

async function getActiveIceCandidateType(peerConnection) {
  const stats = await peerConnection.getStats();
  for (const stat of stats.values()) {
    if (stat.type === 'iceCandidatePair' && stat.state === 'succeeded') {
      const localCandidate = stats.get(stat.localCandidateId);
      const remoteCandidate = stats.get(stat.remoteCandidateId);
      return {
        localType: localCandidate.type,
        remoteType: remoteCandidate.type
      };
    }
  }
  return null;
}

// 使用示例
getActiveIceCandidateType(yourPeerConnectionInstance)
  .then(typeInfo => {
    if (typeInfo) {
      console.log(`本地连接类型: ${typeInfo.localType}`);
      console.log(`远程连接类型: ${typeInfo.remoteType}`);
    } else {
      console.log('未找到已成功的连接候选');
    }
  })
  .catch(err => console.error('获取统计数据失败:', err));

说明:

  • iceCandidatePair类型的统计项中,state为succeeded的是当前正在使用的连接候选对。
  • 该方法比解析SDP更准确,因为getStats()返回的是实时生效的连接状态,而非协商阶段的候选集合。

内容的提问来源于stack exchange,提问作者user558185

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:02:38