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

WebSocketStream: close() method

· 52CE 我爱测

The **`close()`** method of the WebSocketStream interface closes the WebSocket connection. The method optionally accepts an object containing a custom code and/or reason indicating why the connection was closed.

WebSockets API

The close() method of the WebSocketStream interface closes the WebSocket connection. The method optionally accepts an object containing a custom code and/or reason indicating why the connection was closed.

Syntax

close()
close(options)

Parameters

  • options
    • : An options object containing the following properties:
      • closeCode
      • reason
        • : A string representing a human-readable description of the reason why the socket connection is closed. The maximum allowed length for a reason string is 123 bytes. The string is automatically encoded as UTF-8 when the function is invoked.

[!NOTE] Depending on the server setup and status code you use, the server may choose to ignore a custom code in favor of a valid code that is correct for the closing reason. Valid codes are 1000, and any code within the range 3000 to 4999, inclusive.

Return value

None (undefined).

Exceptions

  • SyntaxError DOMException
    • : Thrown if the provided reason is longer than the maximum allowed length of 123 bytes.

Examples

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

setTimeout(() => {
  wss.close({
    closeCode: 1000,
    reason: "That's all folks",
  });
}, 10000);

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

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

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