跳到主要内容

RFC 6455 - WebSocket 协议

  • 状态: Proposed Standard
  • 发布日期: 2011 年 12 月
  • 文档流: IETF
  • 勘误: 无勘误

摘要

WebSocket 协议允许客户端和服务器在单个 TCP 连接上进行全双工通信. WebSocket 协议设计为可在 Web 浏览器和 Web 服务器中实现, 但也可由任何客户端或服务器应用使用.

WebSocket 协议是一个独立的, 基于 TCP 的协议. 它与 HTTP 的唯一关系是其握手会被 HTTP 服务器解释为 Upgrade 请求.


目录


相关资源


相关 RFC

  • RFC 6455: The WebSocket Protocol ← 本文档
  • RFC 7692: WebSocket Compression Extensions
  • RFC 8441: Bootstrapping WebSockets with HTTP/2

快速参考

WebSocket URI 格式

ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
  • ws:// - 未加密连接, 默认端口 80
  • wss:// - TLS 加密连接, 默认端口 443, 生产环境推荐使用

握手示例

客户端请求:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: http://example.com

服务器响应:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

帧类型 (Opcode)

Opcode类型描述
0x0ContinuationContinuation frame
0x1TextText frame (UTF-8)
0x2BinaryBinary frame
0x8CloseClose frame
0x9PingPing frame (heartbeat)
0xAPongPong frame (heartbeat response)

关闭状态码

Code名称描述
1000Normal Closure正常关闭
1001Going Away端点离开, 例如页面导航
1002Protocol Error协议错误
1003Unsupported Data不支持的数据类型
1006Abnormal Closure异常关闭, 未发送 Close frame
1009Message Too Big消息过大
1011Internal Error服务器内部错误

帧结构 (基础格式)

 0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+-------------------------------+
| Extended payload length continued, if payload len == 127 |
+-------------------------------+-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------+-------------------------------+

要点:

  • FIN: 1 表示最终帧, 0 表示后续还有帧
  • MASK: 客户端到服务器必须为 1, 服务器到客户端必须为 0
  • Opcode: 帧类型标识符
  • Payload Length: 数据长度, 0-125 直接表示, 126 使用 16-bit, 127 使用 64-bit

核心术语

英文术语描述
Full-Duplex Communication双向同时通信
Opening Handshake升级到 WebSocket 的 HTTP 握手过程
Closing Handshake优雅关闭连接的过程
Frame数据传输的基本单元
Message由一个或多个帧组成
Masking客户端数据必须进行掩码处理的安全机制
Fragmentation将大型消息拆分为多个帧传输