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
相关推荐
xiaofeichaichai12 小时前
Webpack
前端·webpack·node.js
问心无愧051312 小时前
ctf show web入门111
android·前端·笔记
xujinwei_gingko12 小时前
SpringBoot整合WebSocket
spring boot·后端·websocket
唐某人丶12 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界12 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌13 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel14 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia31114 小时前
https连接传输流程
前端·面试
徐小夕14 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github