跳到主要内容

6. 发送和接收数据

6.1 发送数据

要通过 WebSocket 连接发送数据, endpoint (端点) MUST 将数据封装在 WebSocket frame 中.

发送步骤

  1. 准备要发送的数据
  2. 确定 frame 类型 (Text 或 Binary)
  3. 如果是客户端, 生成 masking key 并 mask 数据
  4. 构造 WebSocket frame
  5. 通过底层 TCP 连接发送

浏览器 API 示例

const ws = new WebSocket('wss://example.com/socket');

// Send text data
ws.send('Hello, Server!');

// Send binary data
const buffer = new ArrayBuffer(8);
ws.send(buffer);

// Send Blob
const blob = new Blob(['Hello'], { type: 'text/plain' });
ws.send(blob);

6.2 接收数据

当 endpoint 接收数据时, 它 MUST 按以下步骤处理:

  1. 读取 frame header
  2. 验证 frame 格式
  3. 如果已 mask, 则 unmask 数据
  4. 根据 Opcode 处理 frame
  5. 如果是分片消息, 重新组装消息
  6. 将完整消息递交给应用层

浏览器 API 示例

ws.onmessage = (event) => {
if (typeof event.data === 'string') {
console.log('Received text:', event.data);
} else if (event.data instanceof ArrayBuffer) {
console.log('Received binary:', event.data);
}
};

参考链接