RTCPeerConnection: icecandidate 事件

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本使用。自 2017 年 9 月以來,它已在瀏覽器中提供。

icecandidate 事件傳送到一個 RTCPeerConnection 物件時,表示:

在頭兩種情況下,事件處理程式應透過信令通道將該 candidate 傳輸給遠端對等端,以便遠端對等端可以將其新增到其遠端 candidate 集合中。

此事件不可取消,也不會冒泡。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("icecandidate", (event) => { })

onicecandidate = (event) => { }

事件型別

一個 RTCPeerConnectionIceEvent。繼承自 Event

Event RTCPeerConnectionIceEvent

事件屬性

一個 RTCPeerConnectionIceEvent 是一個 Event,因此也實現了以下屬性:.

RTCPeerConnectionIceEvent.candidate 只讀

表示包含與事件關聯的 candidate 的 RTCIceCandidate。如果事件指示在此 **generation** 中沒有更多 candidate 可用,則此屬性為空字串("");如果所有傳輸上的 ICE 收集均已完成,則為 null

描述

icecandidate 事件在 RTCPeerConnection 物件上觸發有三個原因。

共享新的 candidate

大多數 icecandidate 事件是為了指示已收集到一個新的 candidate。此 candidate 需要透過您的程式碼管理的信令通道傳遞給遠端對等端。

js
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 收集狀態。

js
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() 的示例:

js
pc.addEventListener("icecandidate", (ev) => {
  if (ev.candidate !== null) {
    sendMessage({
      type: "new-ice-candidate",
      candidate: ev.candidate,
    });
  }
});

您也可以直接設定 onicecandidate 事件處理程式屬性:

js
pc.onicecandidate = (ev) => {
  if (ev.candidate !== null) {
    sendMessage({
      type: "new-ice-candidate",
      candidate: ev.candidate,
    });
  }
};

規範

規範
WebRTC:瀏覽器中的即時通訊
# dom-rtcpeerconnection-onicecandidate

瀏覽器相容性

另見