以Promise风格调用: 不支持
监听 WebSocket 连接关闭事件
function callback
属性 | 类型 | 说明 |
|---|---|---|
| code | number | 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。 |
| reason | string | 如果 from 值是 button,则 target 是触发这次转发事件的 button,否则为 undefined |
// 监听 WebSocket 连接关闭事件
xhs.onSocketClose((res) => {
console.log('WebSocket 连接已关闭');
console.log('关闭状态码:', res.code);
console.log('关闭原因:', res.reason);
// 根据关闭原因执行相应的处理逻辑
if (res.code !== 1000) {
console.error('非正常关闭,尝试重新连接...');
// 这里可以尝试重新连接 WebSocket
reconnectWebSocket();
}
});
// 模拟重新连接的函数
function reconnectWebSocket() {
console.log('正在尝试重新连接 WebSocket...');
xhs.connectSocket({
url: 'wss://example.com/socket',
success: () => {
console.log('WebSocket 重新连接成功');
},
fail: (err) => {
console.error('WebSocket 重新连接失败:', err.errMsg);
}
});
}