子协议(Subprotocol) 是 WebSocket 协议中的一个重要概念,用于在客户端和服务器之间协商和定义更高层次的应用协议。通过子协议,双方可以明确约定在 WebSocket 连接上交换的数据格式和通信规则,从而实现更复杂的交互。
什么是子协议?
在 WebSocket 连接建立的握手阶段,客户端可以请求使用一个或多个子协议。服务器在接受连接时,可以选择其中一个子协议进行通信。子协议的选择有助于确保客户端和服务器之间在数据交换时遵循相同的规则和格式。
RFC 6455(WebSocket 协议标准)对子协议的定义如下:
Subprotocols are application-level protocols layered on top of the WebSocket protocol. They provide a way to define the format of the messages exchanged between the client and the server.
子协议的用途
子协议主要用于以下目的:
定义消息格式:确保客户端和服务器使用相同的数据格式(如 JSON、XML 或自定义格式)进行通信。
指定通信规则:约定如何处理特定类型的消息、事件或操作。
多协议支持:允许在同一 WebSocket 服务器上支持多种不同的应用协议,根据需要选择适当的子协议。
如何使用子协议?
客户端指定子协议
在客户端创建 WebSocket 连接时,可以指定一个或多个子协议。以下是一些常见环境中的示例:
浏览器环境
// 指定一个子协议
const ws = new WebSocket("wss://yourserver.com/socket", "my-protocol");
// 指定多个子协议(服务器会选择其中一个)
const ws = new WebSocket("wss://yourserver.com/socket", ["protocol1", "protocol2"]);Node.js 环境
使用 ws 库时,可以这样指定子协议:
const WebSocket = require('ws');
const ws = new WebSocket('wss://yourserver.com/socket', 'my-protocol');
// 或者
const ws = new WebSocket('wss://yourserver.com/socket', ['protocol1', 'protocol2']);服务器端选择子协议
服务器在握手时会检查客户端请求的子协议,并选择其中一个进行通信。如果服务器不支持任何指定的子协议,它可以拒绝连接或选择不使用子协议。
以下是使用 Node.js 和 ws 库的服务器示例:
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 8080,
handleProtocols: (protocols, request) => {
// 定义服务器支持的子协议
const supportedProtocols = ['my-protocol', 'protocol1'];
for (let protocol of protocols) {
if (supportedProtocols.includes(protocol)) {
return protocol;
}
}
// 如果没有匹配的子协议,可以返回 false 或 null
return false; // 拒绝连接
}
});
wss.on('connection', (ws, request) => {
console.log('子协议:', ws.protocol); // 输出所选的子协议
ws.on('message', (message) => {
console.log('收到消息:', message);
// 根据子协议处理消息
if (ws.protocol === 'my-protocol') {
// 处理 my-protocol 的消息
} else if (ws.protocol === 'protocol1') {
// 处理 protocol1 的消息
}
});
ws.send('连接已建立,使用子协议: ' + ws.protocol);
});子协议与认证
虽然技术上可以利用子协议传递认证信息(如 token),但这并不是子协议的主要设计目的。子协议主要用于定义应用级别的通信规则和数据格式。对于认证,推荐使用以下方法:
查询参数(Query Parameters): 在 WebSocket URL 中附加 token,例如:
const token = "your_token_here"; const ws = new WebSocket(`wss://yourserver.com/socket?token=${token}`);Cookie: 如果 token 存储在 Cookie 中,并且 WebSocket 连接与相同的域名相关联,Cookie 会自动包含在握手请求中。
自定义 HTTP 头部(仅限非浏览器环境): 在 Node.js 中,可以自定义握手时的 HTTP 头部来传递 token。
子协议的示例
假设你有一个聊天应用,你可以定义一个名为 chat 的子协议:
客户端
const ws = new WebSocket("wss://yourserver.com/socket", "chat");
ws.onopen = () => {
console.log('连接已建立,使用子协议:', ws.protocol);
ws.send(JSON.stringify({ type: 'message', content: 'Hello, World!' }));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('收到消息:', message);
};服务器端
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 8080,
handleProtocols: (protocols, request) => {
if (protocols.includes('chat')) {
return 'chat';
}
return false; // 拒绝连接
}
});
wss.on('connection', (ws, request) => {
console.log('子协议:', ws.protocol);
ws.on('message', (message) => {
const data = JSON.parse(message);
if (data.type === 'message') {
// 广播消息给所有连接的客户端
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'message', content: data.content }));
}
});
}
});
ws.send(JSON.stringify({ type: 'system', content: '欢迎来到聊天服务器!' }));
});总结
子协议 是 WebSocket 之上的应用层协议,用于定义数据交换的格式和规则。
使用场景:不同的应用需求(如聊天、游戏、实时更新)可以定义不同的子协议。
认证信息传递:虽然可以通过子协议传递认证信息,但推荐使用查询参数、Cookie 或自定义 HTTP 头部(在非浏览器环境中)。
实现方式:客户端在创建 WebSocket 连接时指定子协议,服务器选择并确认使用的子协议。
通过正确使用子协议,你可以确保 WebSocket 连接中的数据交换符合特定的应用需求,提高通信的效率和可靠性。
最后
以上就是名字长了才好记最近收集整理的关于websocket自定义子协议是什么的全部内容,更多相关websocket自定义子协议是什么内容请搜索靠谱客的其他文章。
发表评论 取消回复