data() {
return {
isSuccess: false, //websocket状态
socketTask: null, //websocket初始化
reconnectCount: 5, //websocket重连次数
}
},
onShow(){
this.connectSocket() //websocket 初始化
},
methods: {
//连接websocket
connectSocket() {
let that = this;
console.log('调用连接websocket')
this.socketTask = uni.connectSocket({
url: clothesPath,
success(res) {
console.log("websocket连接成功", res);
// that.isSuccess = true
},
fail(err) {
console.log("报错", err);
}
},
);
this.socketTask.onOpen(function(res) {
console.log('WebSocket连接已打开!');
that.isSuccess = true
that.heart() //定义心跳机制
})
this.socketTask.onMessage(function(res) {
console.log('收到服务器内容:' + res.data);
/* 处理自己业务逻辑*/
});
this.socketTask.onError(function(res) {
console.log('WebSocket连接打开失败,请检查!');
console.log(res);
// this.isSuccess = false
that.connectSocket()
that.reconnect();
})
// // 监听连接关闭 -
// this.socketTask.onClose((e) => {
// console.log('WebSocket连接关闭!');
// this.socketTask.close()
// clearInterval(that.timer)
// that.timer = ''
// })
},
//进入重新连接
reconnect() {
console.log('进入断线重连');
this.reconnectInterval = setInterval(() => {
if (this.reconnectCount > 0) {
console.log('正在重连第' + this.reconnectCount + '次');
this.socketTask = null;
this.connectSocket()
this.reconnectCount--;
}else{
clearInterval(this.reconnectInterval);
}
},10000)
this.socketTask.close();
},
//向websocket发送消息
sendSocketMessage(msg) {
console.log('发送信息')
return new Promise((reslove, reject) => {
this.socketTask.send({
data: msg,
success(res) {
console.log('发送成功')
reslove(res)
},
fail(res) {
console.log('发送失败')
console.log(res)
reject(res)
}
});
})
},
// 关闭websocket【离开这个页面的时候执行关闭】
closeSocket() {
this.socketTask.close()
console.log('WebSocket关闭!');
},
//定义心跳机制60s
heart() {
let that = this;
clearInterval(this.timer);
this.timer = '';
let msg = {
"type": "heartbeat",
}
this.timer = setInterval(() => {
that.sendSocketMessage(JSON.stringify(msg)).then(res => {
console.log('心跳成功')
}).catch(res => {
console.log('发送失败')
console.log((res))
})
}, 600000)
},
},
websocket 数据实时更新
最新推荐文章于 2024-08-06 21:25:27 发布
该代码段实现了一个WebSocket连接管理器,包括连接初始化、打开、消息接收、错误处理、重连机制以及心跳检测功能。当连接失败时,会按照设定的重连次数尝试重新连接,并在连接成功后发送心跳包以保持连接活跃。
摘要由CSDN通过智能技术生成