RTCDataChannel: readyState 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

只讀 RTCDataChannel 屬性 readyState 返回一個字串,用於指示資料通道底層資料連線的狀態。

一個字串,指示底層資料傳輸的當前狀態,其值是以下值之一:

connecting

使用者代理(瀏覽器)正在建立底層資料傳輸;這是由 RTCPeerConnection.createDataChannel() 建立的新 RTCDataChannel 在啟動連線過程的對等方上的狀態。

open

底層資料傳輸已建立,並且可以在其上傳輸雙向資料。這是 WebRTC 層建立的新 RTCDataChannel 的預設狀態,當遠端對等方建立通道並將其透過 datachannel 事件傳遞給站點或應用時。

closing

正在開始關閉底層資料傳輸的過程。不再可能排隊傳送新訊息,但先前排隊的訊息可能仍在進入 closed 狀態之前傳送或接收。

closed

底層資料傳輸已關閉,或者建立連線的嘗試失敗。

示例

js
const dataChannel = peerConnection.createDataChannel("File Transfer");
const sendQueue = [];

function sendMessage(msg) {
  switch (dataChannel.readyState) {
    case "connecting":
      console.log(`Connection not open; queueing: ${msg}`);
      sendQueue.push(msg);
      break;
    case "open":
      sendQueue.forEach((msg) => dataChannel.send(msg));
      break;
    case "closing":
      console.log(`Attempted to send message while closing: ${msg}`);
      break;
    case "closed":
      console.log("Error! Attempt to send while connection closed.");
      break;
  }
}

規範

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

瀏覽器相容性

另見