前情提要
webrtc的ice candidate并没有现成的回调,来告诉你某个ice candidate连通了。
参考chrome://webrtc-internals/的代码,可以在ice连通后,通过RTCStatsReport对象来获取ICE Candidate pair
获取代码
localPc.oniceconnectionstatechange = (event: Event) => {
if (localPc!.iceConnectionState === 'connected') {
localPc!.getStats(null).then((stats: RTCStatsReport) =>
stats.forEach((report) => {
if (report.type === 'transport') {
let activeCandidatePair = stats.get(report.selectedCandidatePairId)
let remoteCandidate = stats.get(activeCandidatePair.remoteCandidateId)
let localCandidate = stats.get(activeCandidatePair.localCandidateId)
// ipv6
if (localCandidate && localCandidate.address && localCandidate.address.indexOf(':') !== -1) {
console.log(`网络通道:[${localCandidate.address}]:${localCandidate.port}<=>[${remoteCandidate.address}]:${remoteCandidate.port}`)
} else {
console.log(`网络通道:${localCandidate.address}:${localCandidate.port}<=>${remoteCandidate.address}:${remoteCandidate.port}`)
}
console.log('本地candidate', localCandidate)
console.log('远程candidate', remoteCandidate)
}
})
)
} else {
console.log('ice状态变更:')
}
}