在data中定義好需要用到的變量
// 消息類
class MsgContent {
constructor(param = {},action = 'heartbeat',controller = 'Index'){
this.param = param;
this.action = action;
this.controller = controller;
}
}
isSocketClose:false, // 是否關(guān)閉socket
reconnectCount:5, // 重連次數(shù)
heartbeatInterval:"", // 心跳定時(shí)器
isStart:false, // 是否啟動(dòng)設(shè)備
在methods中
sokcet(){
try{
//WebSocket的地址
var url = this.$getUniAppConfig().xhr.socket
// 連接
uni.connectSocket({
url: url,
fail:(err)=>{
_this.$toast(JSON.stringify(err))
}
});
// 連接打開(kāi)
uni.onSocketOpen(function (res) {
console.log('WebSocket打開(kāi)');
//斷線后重連幾次
_this.reconnectCount = 5
// 5秒發(fā)送一次心跳
_this.heartbeatInterval = setInterval(()=>{
_this.sendMsg(new MsgContent({
name:'PING',
id:_this.equipmentData.id
}))
},5000)
});
// 監(jiān)聽(tīng)連接失敗
uni.onSocketError(function (res) {
console.log('WebSocket連接打開(kāi)失敗倡勇,請(qǐng)檢查棒旗!');
//停止發(fā)送心跳
clearInterval(_this.heartbeatInterval)
//如果不是人為關(guān)閉的話,進(jìn)行重連
if(!_this.isSocketClose){
reconnect(url)
}
});
// 監(jiān)聽(tīng)連接關(guān)閉
uni.onSocketClose(function (e) {
console.log('WebSocket連接關(guān)閉磷支!');
clearInterval(_this.heartbeatInterval)
if(!_this.isSocketClose){
reconnect(url)
}
});
// 監(jiān)聽(tīng)收到信息
uni.onSocketMessage(function (res) {
uni.hideLoading()
let serverData = JSON.parse(res.data)
//與后端規(guī)定好返回值分別代表什么纽甘,寫業(yè)務(wù)邏輯
//判斷是否為同一設(shè)備,比如用戶去鏈接了其他設(shè)備,避免設(shè)備鏈接混淆
if(_this.equipmentId== serverData.data.user_equipment_type_id) {
if(serverData.code == 0) {
...
}else if(serverData.code == 1){
...
});
const reconnect = this.$debounce((url) =>{ // 斷線重連
console.log(`第${5-this.reconnectCount}次斷線重連中...`)
this.reconnectCount --
if(this.reconnectCount <= 0){
this.$toast("error")
//如果重連次數(shù)為0钉跷,則做退出處理
uni.navigateBack({
delta:1
})
}else{
// 連接
uni.connectSocket({
url: url,
});
}
},3000)
}catch(e){
}
}
sendMsg(msg){ //向后端發(fā)送命令
msg = JSON.stringify(msg)
try{
//通過(guò) WebSocket 連接發(fā)送數(shù)據(jù)
uni.sendSocketMessage({
data: msg
});
}catch(e){
this.isSocketClose = true;
uni.closeSocket()
}
},
Tapstart(){ // 啟動(dòng)
uni.showLoading({
title:'設(shè)備啟動(dòng)中...'
})
this.sendMsg(new MsgContent({
//啟動(dòng)設(shè)備需要的請(qǐng)求參數(shù)
id:_this.equipmentData.id,
equipment_status:_this.equipmentData.equipment_status,
uid:_this.equipmentData.uid
},"start_equipment"))
},