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
相关推荐
林恒smileZAZ36 分钟前
Vue<前端页面版本检测>
前端·javascript·vue.js
码事漫谈4 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
许杰小刀4 小时前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
我是Superman丶5 小时前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭5 小时前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
xiaokuangren_5 小时前
前端css颜色
前端·css
Huanzhi_Lin5 小时前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
hoiii1876 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
anOnion6 小时前
构建无障碍组件之Meter Pattern
前端·html·交互设计
小码哥_常6 小时前
Spring Boot配置diff:解锁配置管理新姿势
前端