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
相关推荐
灵感__idea5 小时前
JavaScript高级程序设计(第5版):好的编程就是掌控感
前端·javascript·程序员
烛阴7 小时前
Mix
前端·webgl
代码续发7 小时前
前端组件梳理
前端
试图让你心动7 小时前
原生input添加删除图标类似vue里面移入显示删除[jquery]
前端·vue.js·jquery
何双新7 小时前
基于Tornado的WebSocket实时聊天系统:从零到一构建与解析
python·websocket·tornado
陈不知代码8 小时前
uniapp创建vue3+ts+pinia+sass项目
前端·uni-app·sass
小王码农记8 小时前
sass中@mixin与 @include
前端·sass
源码_V_saaskw8 小时前
JAVA图文短视频交友+自营商城系统源码支持小程序+Android+IOS+H5
java·微信小程序·小程序·uni-app·音视频·交友
陈琦鹏8 小时前
轻松管理 WebSocket 连接!easy-websocket-client
前端·vue.js·websocket
hui函数8 小时前
掌握JavaScript函数封装与作用域
前端·javascript