6. 发送和接收数据
6.1 发送数据
要通过 WebSocket 连接发送数据, endpoint (端点) MUST 将数据封装在 WebSocket frame 中.
发送步骤
- 准备要发送的数据
- 确定 frame 类型 (Text 或 Binary)
- 如果是客户端, 生成 masking key 并 mask 数据
- 构造 WebSocket frame
- 通过底层 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 按以下步骤处理:
- 读取 frame header
- 验证 frame 格式
- 如果已 mask, 则 unmask 数据
- 根据 Opcode 处理 frame
- 如果是分片消息, 重新组装消息
- 将完整消息递交给应用层
浏览器 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);
}
};
参考链接
- 上一章: 5. Data Framing
- 下一章: 7. 关闭连接