websocket作为一种在单个TCP上连接的全双工通信的协议,可实现更快捷的数据交换,允许服务器主动向客户端发送,接下来将介绍一下如何在uniapp中使用websocket:
使用变量:
socketTask: null,
heartbeatInterval: null, //心跳定时器
interval: 150000, //心跳时间间隔
manualClose: false, //是否为手动断开连接
reconnectAttempts: 0, //重连尝试次数
maxReconnectAttempts: 5, //最大重连次数
reconnectDelay: 1000, //初始重连延迟
初连接:
初始化一个websocket任务对象socketTask,实现核心方法的数据处理操作
onOpen():监听websocket连接打开事件
onMessage():监听收到服务器消息,在接收到信息后,可根据需求自行进行数据处理操作
onError():监听错误事件
onClose():监听连接关闭事件
initWebsocket() {
if (this.socketTask) {
return;
}
let th = this;
this.reconnectDelay = 1000; // 初始重连延迟(毫秒)
const connect = () => {
this.socketTask = uni.connectSocket({
url: url,
header: {},
success: () => {
console.log(`WebSocket 开始连接`);
},
fail: (err) => {
console.error(`连接失败`, err);
this.handleReconnect();
}
});
// 监听 WebSocket 打开事件
this.socketTask.onOpen((res) => {
console.log("WebSocket 连接已打开(onOpen)", res);
this.reconnectAttempts = 0; // 重置重连计数器
this.reconnectDelay = 1000; // 重置重连延迟
this.sendHeartbeat();
this.heartbeatInterval = setInterval(() => {
this.sendHeartbeat();
}, th.interval); // 30秒一次心跳
});
// 监听消息接收
this.socketTask.onMessage((res) => {
console.log("收到服务器消息:");
try {} catch (e) {
console.error("消息解析错误:", e);
}
});
// 监听错误
this.socketTask.onError((err) => {
console.error("WebSocket 错误:", err);
this.handleReconnect();
});
// 监听关闭
this.socketTask.onClose((res) => {
console.log("WebSocket 连接已关闭:", res);
this.clearConnection();
// 如果不是主动关闭,则尝试重连
if (!this.manualClose) {
this.handleReconnect();
}
});
};
connect();
},
客户端主动发送消息:
这里有两种应用方式:
1、发送心跳,防止断开连接
this.socketTask.send({
data: JSON.stringify({
type: "ping",
timestamp: Date.now()
}),
success: () => console.log(`心跳发送成功`),
fail: (err) => {
console.error(`心跳发送失败`, err);
this.clearConnection();
this.handleReconnect();
}
});
2、发送具体消息
this.socketTask.send({
data:data,
success: (res) => {},
fail: (err) => {}
});
断线重连:
如果连接失败或者连接断开,尝试重连,并设置最大重连次数,每次重连延长间隔重连时间
handleReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.warn(`已达到最大重连次数(${this.maxReconnectAttempts}),停止重连`);
return;
}
this.reconnectAttempts++;
let delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts), 30000);
console.log(`将在 ${delay}ms 后尝试第 ${this.reconnectAttempts} 次重连...`);
setTimeout(() => {
if (!this.manualClose) {
this.initWebsocket();
}
}, delay);
},
清理websocket
在页面关闭或者销毁的时候,清理掉所有的连接和定时器
// 清理连接
clearConnection() {
console.log("关闭连接");
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
if (this.socketTask) {
this.socketTask.close();
this.socketTask = null;
}
},
// 手动关闭连接
closeConnection() {
this.manualClose = true;
this.clearConnection();
},
以上便是websocket核心使用,某些细节方面还有赖于开发者具体实现