为什么要心跳检测
使用微信小程序WebSocket时,WebSocket在一定的时间没有进行通信就会断开连接,所以需要使用心跳检测。
那么心跳检测是什么呢,心跳检测顾名思义就是和人心脏动一样,客户端在一定的时间间隔内给服务器发送信息,服务器再返回预定好的信息,防止WebSocket断开。这样就是心跳监测了。
- 这是心跳的代码
let heartCheck = {
timeout: 100000,
timeoutObj: null,
serverTimeoutObj: null,
//清除定时器
reset: function () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
// 发送约定好的信息
this.timeoutObj = setTimeout(()=> {
let msg={
msg:'ping',
toUser:'root'
}
wx.sendSocketMessage({
data:JSON.stringify(msg)})
const that=this;
//连接WebSocket
this.serverTimeoutObj = setTimeout(() =>{
wx.closeSocket();
}, this.timeout);
}, this.timeout);
}
};
2.断开重新连接代码
//重新连接,这是重新连接的代码,lockReconnect是当达到最大重新连接次数的时候不在执行重新连接的代码
reconnect(){
console.log("重新连接");
if (this.lockReconnect) return;
this.lockReconnect = true;
clearTimeout(this.timer)
console.log(this.globalData.limit<10);
if (this.globalData.limit<10){
this.timer = setTimeout(() => {
this.connectStart();
this.lockReconnect = false;
}, 5000);
//limit是重新连接的次数,最大为10次
this.globalData.limit=this.globalData.limit+1
}
},
//我这里是在全局app.js写的,在单个页面就加在data里
globalData: {
limit:0,
closure:true,
userInfo: null
}
3.在页面或者小程序加载的时候建立连接并加上心跳检测
onLaunch() {
this.connectStart()
},
//第一步与socket建立连接
connectStart(){
const that=this;
wx.connectSocket({
url:url+wx.getStorageSync('id'),//填写连接的网址
header: {
'content-type': 'application/json'
},
success: (res) => {
console.log("进入聊天", res)
this.onSocketMessage()
},
fail: (err) => {
wx.showToast({
title: '网络异常!',
})
console.log(err)
},
})
},
//第二步在连接成功后添加心跳监测
onSocketMessage(){
//接收消息
const that=this;
wx.onSocketMessage(function(res) {
console.log('收到服务器内容:', JSON.parse(res.data),)
})
// 连接成功
wx.onSocketOpen((res) => {
console.log('WebSocket 成功连接', res)
//心跳检测
heartCheck.reset().start()
})
//连接失败
wx.onSocketError((err) => {
console.log('websocket连接失败', err);
重新连接
this.reconnect()
})
wx.onSocketClose((res) =>{
console.log('WebSocket 已关闭!')
if (this.globalData.closure) {
//重新连接
this.reconnect()
}else{}
})
},