在data中定义好需要用到的变量
// 消息类
class MsgContent {
constructor(param = {},action = 'heartbeat',controller = 'Index'){
this.param = param;
this.action = action;
this.controller = controller;
}
}
isSocketClose:false, // 是否关闭socket
reconnectCount:5, // 重连次数
heartbeatInterval:"", // 心跳定时器
isStart:false, // 是否启动设备
在methods中
sokcet(){
try{
//WebSocket的地址
var url = this.$getUniAppConfig().xhr.socket
// 连接
uni.connectSocket({
url: url,
fail:(err)=>{
_this.$toast(JSON.stringify(err))
}
});
// 连接打开
uni.onSocketOpen(function (res) {
console.log('WebSocket打开');
//断线后重连几次
_this.reconnectCount = 5
// 5秒发送一次心跳
_this.heartbeatInterval = setInterval(()=>{
_this.sendMsg(new MsgContent({
name:'PING',
id:_this.equipmentData.id
}))
},5000)
});
// 监听连接失败
uni.onSocketError(function (res) {
console.log('WebSocket连接打开失败,请检查!');
//停止发送心跳
clearInterval(_this.heartbeatInterval)
//如果不是人为关闭的话,进行重连
if(!_this.isSocketClose){
reconnect(url)
}
});
// 监听连接关闭
uni.onSocketClose(function (e) {
console.log('WebSocket连接关闭!');
clearInterval(_this.heartbeatInterval)
if(!_this.isSocketClose){
reconnect(url)
}
});
// 监听收到信息
uni.onSocketMessage(function (res) {
uni.hideLoading()
let serverData = JSON.parse(res.data)
//与后端规定好返回值分别代表什么,写业务逻辑
//判断是否为同一设备,比如用户去链接了其他设备,避免设备链接混淆
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")
//如果重连次数为0,则做退出处理
uni.navigateBack({
delta:1
})
}else{
// 连接
uni.connectSocket({
url: url,
});
}
},3000)
}catch(e){
}
}
sendMsg(msg){ //向后端发送命令
msg = JSON.stringify(msg)
try{
//通过 WebSocket 连接发送数据
uni.sendSocketMessage({
data: msg
});
}catch(e){
this.isSocketClose = true;
uni.closeSocket()
}
},
Tapstart(){ // 启动
uni.showLoading({
title:'设备启动中...'
})
this.sendMsg(new MsgContent({
//启动设备需要的请求参数
id:_this.equipmentData.id,
equipment_status:_this.equipmentData.equipment_status,
uid:_this.equipmentData.uid
},"start_equipment"))
},