RTCPeerConnection: icecandidate 事件
当 icecandidate 事件发送到一个 RTCPeerConnection 对象时,表示:
- 通过调用
RTCPeerConnection.setLocalDescription(),一个RTCIceCandidate被识别并添加到本地对等端。 - 针对特定用户名片段和密码组合(一个 **generation**)的所有
RTCIceCandidate都已被识别并添加。 - 所有传输上的 ICE 收集(gathering)已完成。
在头两种情况下,事件处理程序应通过信令通道将该 candidate 传输给远程对等端,以便远程对等端可以将其添加到其远程 candidate 集合中。
此事件不可取消,也不会冒泡。
语法
在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。
addEventListener("icecandidate", (event) => { })
onicecandidate = (event) => { }
事件类型
一个 RTCPeerConnectionIceEvent。继承自 Event。
事件属性
一个 RTCPeerConnectionIceEvent 是一个 Event,因此也实现了以下属性:.
RTCPeerConnectionIceEvent.candidate只读-
表示包含与事件关联的 candidate 的
RTCIceCandidate。如果事件指示在此 **generation** 中没有更多 candidate 可用,则此属性为空字符串("");如果所有传输上的 ICE 收集均已完成,则为null。
描述
icecandidate 事件在 RTCPeerConnection 对象上触发有三个原因。
共享新的 candidate
大多数 icecandidate 事件是为了指示已收集到一个新的 candidate。此 candidate 需要通过您的代码管理的信令通道传递给远程对等端。
rtcPeerConnection.onicecandidate = (event) => {
if (event.candidate !== null) {
sendCandidateToRemotePeer(event.candidate);
} else {
/* there are no more candidates coming during this negotiation */
}
};
远程对等端在收到 candidate 后,将通过调用 addIceCandidate() 并传入您通过信令服务器传递的 candidate 字符串,将其添加到其 candidate 池中。
指示 candidate generation 结束
当 ICE 协商会话用尽为特定 RTCIceTransport 提供的 candidate 时,意味着该 **generation** 的 candidate 收集已完成。通过一个 icecandidate 事件来指示这一点,该事件的 candidate 字符串为空("")。
您应该像处理标准 candidate 一样,将此信息传递给远程对等端,如上面 共享新的 candidate 部分所述。这确保了远程对等端也收到了“无更多 candidate”的通知。正如您在前一节代码中看到的,所有 candidate 都会发送给另一方,包括可能具有空 candidate 字符串的 candidate。只有当事件的 candidate 属性为 null 的 candidate 才不会通过信令连接转发。
“无更多 candidate”的指示在 Trickle ICE 草案规范的第 9.3 节 中有描述(请注意,随着规范的不断修订,章节号可能会发生变化)。
指示 ICE 收集已完成
一旦所有 ICE 传输都完成了 candidate 的收集,并且 RTCPeerConnection 对象的 iceGatheringState 属性变为 complete,就会发送一个 icecandidate 事件,并将 candidate 的值设置为 null。
此信号的存在是为了向后兼容,不需要转发给远程对等端(这就是为什么上面的代码片段会检查 event.candidate 是否为 null,然后再转发 candidate)。
如果您需要在不再预期有更多 candidate 时执行任何特殊操作,最好通过监听 icegatheringstatechange 事件来监视 ICE 收集状态。
pc.addEventListener("icegatheringstatechange", (ev) => {
switch (pc.iceGatheringState) {
case "new":
/* gathering is either just starting or has been reset */
break;
case "gathering":
/* gathering has begun or is ongoing */
break;
case "complete":
/* gathering has ended */
break;
}
});
正如您在此示例中看到的,icegatheringstatechange 事件会通知您 RTCPeerConnection 对象的 iceGatheringState 属性值何时更新。如果该值为 complete,您就知道 ICE 收集刚刚结束。
这比查看单个 ICE 消息以指示 ICE 会话已完成的方法更可靠。
示例
此示例创建了一个简单的 icecandidate 事件处理程序,它使用一个名为 sendMessage() 的函数通过信令服务器创建并发送对远程对等端的回复。
首先,一个使用 addEventListener() 的示例:
pc.addEventListener("icecandidate", (ev) => {
if (ev.candidate !== null) {
sendMessage({
type: "new-ice-candidate",
candidate: ev.candidate,
});
}
});
您也可以直接设置 onicecandidate 事件处理程序属性:
pc.onicecandidate = (ev) => {
if (ev.candidate !== null) {
sendMessage({
type: "new-ice-candidate",
candidate: ev.candidate,
});
}
};
规范
| 规范 |
|---|
| WebRTC:浏览器中的实时通信 # dom-rtcpeerconnection-onicecandidate |
浏览器兼容性
加载中…