uniapp socket 封装 (可拿去直接用)

示例代码:

javascript 复制代码
class WebSocketClient {
	constructor(url, options = {}) {
		this.url = url;
		this.options = options;
		this.socket = null;
		this.reconnectAttempts = 0;
		this.maxReconnectAttempts = options.maxReconnectAttempts || 5;
		this.reconnectInterval = options.reconnectInterval || 5000;
		this.heartbeatInterval = options.heartbeatInterval || 30000;
		this.heartbeatTimer = null;
		this.messageQueue = [];
		this.eventListeners = {};
		this.isConnected = false;
	}

	connect() {
		this.socket = uni.connectSocket({
			url: this.url,
			success: () => {
				uni.onSocketOpen((res) => {
					this.isConnected = true;
					this.reconnectAttempts = 0;
					this.startHeartbeat();
					this.flushMessageQueue();
					this.emit('open');
				})

				uni.onSocketMessage((res) => {
					this.emit('message', res.data);
				})

				uni.onSocketClose((res)=>{
					this.isConnected = false;
					this.stopHeartbeat();
					this.emit('close');
					this.handleReconnect();
				})
				uni.onSocketError((error)=>{
					this.emit('error', error);
				})
			}
		});
		console.log(this.socket);
	}

	send(message) {
		if (this.isConnected) {
			uni.sendSocketMessage({
				data: JSON.stringify(message)
			})
		} else {
			this.messageQueue.push(message);
		}
	}

	flushMessageQueue() {
		while (this.messageQueue.length > 0 && this.isConnected) {
			const message = this.messageQueue.shift();
			uni.sendSocketMessage({
				data: JSON.stringify(message)
			})
		}
	}

	startHeartbeat() {
		this.stopHeartbeat();
		this.heartbeatTimer = setInterval(() => {
			if (this.isConnected) {
				this.send({
					type: 'heartbeat'
				});
			}
		}, this.heartbeatInterval);
	}

	stopHeartbeat() {
		if (this.heartbeatTimer) {
			clearInterval(this.heartbeatTimer);
			this.heartbeatTimer = null;
		}
	}

	handleReconnect() {
		if (this.reconnectAttempts < this.maxReconnectAttempts) {
			this.reconnectAttempts++;
			setTimeout(() => {
				this.connect();
			}, this.reconnectInterval);
		}
	}

	on(event, callback) {
		if (!this.eventListeners[event]) {
			this.eventListeners[event] = [];
		}
		this.eventListeners[event].push(callback);
	}

	off(event, callback) {
		if (this.eventListeners[event]) {
			this.eventListeners[event] = this.eventListeners[event].filter(
				(cb) => cb !== callback
			);
		}
	}

	emit(event, ...args) {
		if (this.eventListeners[event]) {
			this.eventListeners[event].forEach((callback) => {
				callback(...args);
			});
		}
	}

	close() {
		this.stopHeartbeat();
		this.socket.close({});
	}
}

export default WebSocketClient;

使用方式:

javascript 复制代码
//地址和后端约定好就行
const socket = new WebSocketClient('wss://example.net/websocket')
socket.connect() //连接
socket.send({
	//这里写后端需要的东西
})
//这里不一定是 message,和后端约定好
socket.on('message',(res)=>{
    
})

socket.startHeartbeat() //开始心跳
socket.stopHeartbeat() //结束心跳
socket.close() //关闭socket
相关推荐
正在学习前端的---小方同学1 小时前
vue-easy-tree树状结构
前端·javascript·vue.js
键盘不能没有CV键4 小时前
【图片处理】✈️HTML转图片字体异常处理
前端·javascript·html
yantuguiguziPGJ5 小时前
WPF 联合 Web 开发调试流程梳理(基于 Microsoft.Web.WebView2)
前端·microsoft·wpf
大飞记Python5 小时前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django
tsumikistep6 小时前
【前端】前端运行环境的结构
前端
你的人类朋友6 小时前
【Node】认识multer库
前端·javascript·后端
Aitter6 小时前
PDF和Word文件转换为Markdown的技术实现
前端·ai编程
mapbar_front7 小时前
面试问题—上家公司的离职原因
前端·面试
昔人'8 小时前
css使用 :where() 来简化大型 CSS 选择器列表
前端·css
昔人'8 小时前
css `dorp-shadow`
前端·css