使用 WebSocket API 发送 wss 请求
WebSocket 协议支持加密连接(wss),与 HTTP 和 HTTPS 类似,wss 是 WebSocket 的安全版本。以下是如何在 JavaScript 中使用 WebSocket API 发送 wss 请求。
创建 WebSocket 连接
const socket = new WebSocket('wss://example.com/socket');
监听连接事件
WebSocket 对象提供多个事件,用于处理连接的不同阶段:
socket.onopen = function(event) {
console.log('WebSocket 连接已建立');
socket.send('Hello Server!');
};
socket.onmessage = function(event) {
console.log('收到服务器消息:', event.data);
};
socket.onclose = function(event) {
console.log('WebSocket 连接已关闭:', event.code, event.reason);
};
socket.onerror = function(error) {
console.error('WebSocket 错误:', error);
};
发送数据
连接建立后,可以使用 send 方法发送数据:
socket.send('这是一条文本消息');
socket.send(JSON.stringify({ key: 'value' }));
关闭连接
主动关闭连接:
socket.close(1000, '正常关闭');
处理二进制数据
WebSocket 支持发送和接收二进制数据:
socket.binaryType = 'arraybuffer';
socket.onmessage = function(event) {
if (event.data instanceof ArrayBuffer) {
const buffer = event.data;
console.log('收到二进制数据:', buffer);
}
};
const buffer = new ArrayBuffer(8);
socket.send(buffer);
添加自定义请求头
浏览器端的 WebSocket API 不支持直接设置请求头。如果需要认证,通常采用以下方式:
-
在 URL 中传递 token:
const token = 'your_token'; const socket = new WebSocket(`wss://example.com/socket?token=${token}`); -
连接建立后发送认证消息:
socket.onopen = function() { socket.send(JSON.stringify({ type: 'auth', token: 'your_token' })); };
重连机制
实现简单的断线重连逻辑:
let socket;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
function connect() {
socket = new WebSocket('wss://example.com/socket');
socket.onclose = function() {
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
setTimeout(connect, 1000 * reconnectAttempts);
}
};
}
connect();
浏览器兼容性
大多数现代浏览器都支持 WebSocket API,包括:
- Chrome 16+
- Firefox 11+
- Safari 7+
- Edge 12+
- Opera 12.1+
对于不支持的环境,可以使用 polyfill 如 Socket.IO 或 SockJS。
安全注意事项
- 始终使用 wss 而非 ws,除非在本地开发环境
- 验证服务器发来的消息
- 设置合理的消息大小限制
- 处理连接中断的异常情况
使用第三方库
对于更复杂的需求,可以考虑使用以下库:
-
Socket.IO:
const socket = io('wss://example.com', { transports: ['websocket'] }); -
SockJS:
const socket = new SockJS('https://example.com/socket');
这些库提供了额外的功能如自动重连、心跳检测和回退机制。
2121

被折叠的 条评论
为什么被折叠?



