uni-app 封装websocket 心跳检测,开箱即用

javascript 复制代码
class websocketUtils {
	constructor(url, needbeat, options = {}) {
		this.needbeat = needbeat;
		this.url = url;
		this.options = options;
		this.ws = null;
		this.heartbeatInterval = options.heartbeatInterval || 10000; // 心跳间隔,默认为10秒  
		this.reconnectInterval = options.reconnectInterval || 5000; // 重连间隔,默认为5秒  
		this.reconnectAttempts = options.reconnectAttempts || Infinity; // 最大重连次数,默认为无限次  
		this.reconnectCount = 0;

		this.initWebSocket();
	}

	initWebSocket() {
		this.ws = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log('WebSocket连接成功');
				if (this.needbeat) {
					this.startHeartbeat();
				}
				this.onOpen();
			},
			fail: (err) => {
				console.error('WebSocket连接失败', err);
				this.reconnect();
			}
		});


		// 监听WebSocket接收到服务器的消息事件  
		this.ws.onMessage((result) => {
			// const textDecoder = new TextDecoder();
			// let text = textDecoder.decode(result.data)
			// console.log('自定义处理消息:',result);
			this.onMessage(result);
			// 收到消息后,可能需要重置心跳计时器  
			// 是否需要心跳选择器
			if (this.needbeat) {
				this.resetHeartbeat();
			}
		})
		// 监听WebSocket关闭事件  
		this.ws.onClose(res => {
			console.log('WebSocket连接已关闭', res);
			this.onClose();
			this.reconnect();
		});

		// 监听WebSocket错误事件  
		this.ws.onError(err => {
			console.error('WebSocket发生错误', err);
			this.onError(err);
			this.reconnect();
		});
	}

	// 发送消息  
	send(data) {
		if (this.ws) {
			this.ws.send({
				data: data,
				success: () => {
					console.log('消息发送成功');
				},
				fail: (err) => {
					console.error('消息发送失败', err);
				}
			})
		}
	}

	// 心跳检测  
	startHeartbeat() {
		this.heartbeatTimer = setInterval(() => {
			this.sendHeartbeat();
		}, this.heartbeatInterval);
	}

	// 重置心跳计时器  
	resetHeartbeat() {
		clearInterval(this.heartbeatTimer);
		this.startHeartbeat();
	}

	// 发送心跳消息  
	sendHeartbeat() {
		this.send('ping'); // 假设心跳消息为'ping'  
	}

	// 重连逻辑  
	reconnect() {
		if (this.reconnectCount < this.reconnectAttempts) {
			setTimeout(() => {
				this.initWebSocket();
				this.reconnectCount++;
			}, this.reconnectInterval);
		}
	}

	// 自定义事件处理  
	onOpen() {}
	onMessage(data) {}
	onClose() {}
	onError(err) {}

	// 关闭WebSocket连接  
	close() {
		if (this.ws) {
			this.ws.close({
				success: () => {
					console.log('WebSocket连接已关闭');
				},
				fail: (err) => {
					console.error("wss关闭失败->", err)
				}
			});
			clearInterval(this.heartbeatTimer);
			this.ws = null;
		}
	}
}
export default websocketUtils;

使用

javascript 复制代码
let socket = new websocketUtils(wss_.url, false, {
		heartbeatInterval: 5000,
		reconnectInterval: 3000,
		reconnectAttempts: 5
});

socket.onMessage = function(evt) {
  //获取消息
};

socket.send(message);//发送消息
socket.close();//关闭sockett
相关推荐
FPGA技术实战41 分钟前
基于XADC IP核的FPGA芯片温度读取设计
网络协议·tcp/ip·fpga开发
老蒋新思维1 小时前
范式重构:从场景锚点到价值闭环——AI智能体落地知识产业的非技术视角|创客匠人
网络·人工智能·网络协议·tcp/ip·数据挖掘·创始人ip·创客匠人
ICT技术最前线2 小时前
电信宽带怎么申请公网ip?企业组网避坑指南
网络·网络协议·tcp/ip·电信宽带
Misnearch2 小时前
通信方式了解
websocket·全双工·单工·半双工
2501_915106322 小时前
全面理解 iOS 帧率,构建从渲染到系统行为的多工具协同流畅度分析体系
android·ios·小程序·https·uni-app·iphone·webview
2501_916008894 小时前
iOS 能耗检测的工程化方法,构建多工具协同的电量分析与性能能效体系
android·ios·小程序·https·uni-app·iphone·webview
老蒋新思维4 小时前
创客匠人万人峰会启示:AI+IP 生态重构,知识变现进入 “共生增长” 时代
网络·人工智能·网络协议·tcp/ip·重构·创始人ip·创客匠人
上海云盾-小余4 小时前
TCP业务DDoS防护专项方案
网络协议·tcp/ip·ddos
济南壹软网络科技有限公司4 小时前
综合社交服务平台的技术架构与实践:构建高可用、多端覆盖的互动生态
uni-app·php·开源源码·陪玩陪聊h5
apihz5 小时前
反向DNS查询与蜘蛛验证免费API接口详细教程
android·开发语言·数据库·网络协议·tcp/ip·dubbo