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
相关推荐
..过云雨9 分钟前
网络计算器实现 - 自定义套接字+序列化+守护进程
网络·网络协议·tcp/ip
三两肉1 小时前
HTTPS ECDHE 握手全解析
网络协议·https·github·rsa·echde
txinyu的博客2 小时前
HTTP服务实现用户级窗口限流
开发语言·c++·分布式·网络协议·http
掘根3 小时前
【仿Muduo库项目】HTTP模块1——Util子模块
网络·网络协议·http
Mr -老鬼4 小时前
移动端跨平台适配技术框架:从发展到展望
android·ios·小程序·uni-app
CCPC不拿奖不改名5 小时前
网络与API:从HTTP协议视角理解网络分层原理+面试习题
开发语言·网络·python·网络协议·学习·http·面试
liulilittle5 小时前
OPENPPP2 网络驱动模式
开发语言·网络·c++·网络协议·信息与通信·通信
tzy2335 小时前
分享一个 HTTP(S) 代理&抓包工具,拦截和Mock Web客户端请求和服务端响应
前端·网络协议·http
mudtools5 小时前
飞书 .NET SDK 事件处理的幂等性与去重机制
websocket·.net·飞书·webhook
小李独爱秋6 小时前
计算机网络经典问题透视:MD5报文是什么?有什么特点?
网络·网络协议·计算机网络·网络安全·信息与通信·信号处理