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
相关推荐
qq_424409193 小时前
uniapp的app项目,某个页面长时间无操作,返回首页
前端·vue.js·uni-app
2501_915918413 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
不知名It水手5 小时前
uniapp运行项目到ios基座
ios·uni-app·cocoa
hunzi_15 小时前
搭建商城系统
java·uni-app·php
合作小小程序员小小店8 小时前
web网页,在线%食谱推荐系统%分析系统demo,基于vscode,uniapp,vue,java,jdk,springboot,mysql数据库
vue.js·spring boot·vscode·spring·uni-app
普宁彭于晏9 小时前
Uni-app 生命周期与钩子:程序的“生命”旅程
uni-app·vue
程序小武9 小时前
网络请求的基本概念、原理及生活化解析
网络协议
甘露寺10 小时前
HTTP 请求体类型详解:选择最适合的数据提交格式
网络·网络协议·http
傻啦嘿哟11 小时前
长效住宅代理IP:反爬虫战场上的隐形盾牌
爬虫·网络协议·tcp/ip
CRMEB定制开发11 小时前
CRMEB Pro版前端环境配置指南
前端·微信小程序·uni-app·商城源码·微信商城·crmeb