大网数据广告活动
Web 标准与前端开发

WebSocketStream: opened property

· 52CE 我爱测

The **`opened`** read-only property of the WebSocketStream interface returns a Promise that fulfills with an object once the socket connection is successfully opened. Among other features, this object contains a ReadableStream and a WritableStream instance for receiving and sendi

WebSockets API

The opened read-only property of the WebSocketStream interface returns a Promise that fulfills with an object once the socket connection is successfully opened. Among other features, this object contains a ReadableStream and a WritableStream instance for receiving and sending data on the connection.

Value

A promise, which fulfills with an object containing the following properties:

  • extensions
    • : A string representing any extensions applied to the WebSocketStream. Such extensions are not currently defined, but may be in the future. Currently returns an empty string.
  • protocol
    • : A string representing the sub-protocol used to open the current WebSocket connection (chosen from the options specified in the protocols option of the WebSocketStream() constructor). Returns an empty string if no sub-protocol has been used to open the connection (i.e., no sub-protocol options were included in the constructor call).
  • readable
    • : A ReadableStream instance. Call ReadableStream.getReader() on it to obtain a ReadableStreamDefaultReader instance that can be used to read incoming WebSocket data.
  • writable
    • : A WritableStream instance. Call WritableStream.getWriter() on it to obtain a WritableStreamDefaultWriter instance that can be used to write data to the WebSocket connection.

The promise rejects if the WebSocket connection fails.

Examples

const wsURL = "wss://127.0.0.1/";
const wss = new WebSocketStream(wsURL);

async function start() {
  const { readable, writable, extensions, protocol } = await wss.opened;

  const reader = readable.getReader();
  const writer = writable.getWriter();

  writer.write("ping");

  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }

    setTimeout(() => {
      writer.write("ping");
    }, 5000);
  }
}

See Using WebSocketStream to write a client for a complete example with full explanation.

Specifications

Not currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。