connetWebsocket() { // wbsocket逻辑
that = this;// 保存this指向
if( webSocket ) that.closeWebSocket(); // 先关 再开 避免多次重复连接
webSocket = wx.connectSocket({
url: ‘你的服务器地址‘,
header:{
"Authorization" : getEncryToken(wx.getStorageSync(_token)), // 加密的token 这是我们的项目需要
}
})
wx.onSocketOpen(function (res) { // 打开webSocket
console.log(‘WebSocket连接已打开!‘)
})
wx.onSocketMessage(function (res) { // 接收数据
console.log(res)
})
wx.onSocketError(function(){ //这里是监听链接出错
that.readConnectWebSocket()
})
wx.onSocketClose(function (res) { //监测webSocket关闭
automaticClose && that.readConnectWebSocket() // 只有是自动断开时才开启重连 这判断挺重要
})
},
closeWebSocket(){ // 手动关闭webSocket
webSocket.close({
success(){
webSocket = null;
console.log(‘webSocket关闭成功‘)
}
})
},
readConnectWebSocket(){ // 重新连接webSocket
clearTimeout(setTimer); // 先关闭定时器
if( num <= 5 ){
num += 1; // 每次重连一次num递增1
num <= 3? t = num*5:t = t*2; // t的值每次为 5 10 15 30 60
setTimer = setTimeout(function name(params) {
that.connetWebsocket()
},t*1000)
}else{ //5次链接都失败走这里
that.startLogTimer() // startLogTimer为一个开启setInterval的函数
}
},
onShow(){