websocket 数据实时更新

该代码段实现了一个WebSocket连接管理器,包括连接初始化、打开、消息接收、错误处理、重连机制以及心跳检测功能。当连接失败时,会按照设定的重连次数尝试重新连接,并在连接成功后发送心跳包以保持连接活跃。
摘要由CSDN通过智能技术生成
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)
			},
},

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值