/** * 小程序 WebSocket 通讯封装参考 */ class ChatSocket { constructor(url) { this.url = url; this.socketTask = null; this.isOpen = false; this.reconnectCount = 0; this.maxReconnect = 5; this.timer = null; this.onMessageCallback = null; } // 初始化连接 connect(token) { if (this.isOpen) return; this.socketTask = uni.connectSocket({ url: `${this.url}?token=${token}`, success: () => { console.log('WebSocket 连接发起成功'); } }); this.socketTask.onOpen(() => { console.log('WebSocket 已连接'); this.isOpen = true; this.reconnectCount = 0; this.startHeartbeat(); }); this.socketTask.onMessage((res) => { const data = JSON.parse(res.data); if (this.onMessageCallback) { this.onMessageCallback(data); } }); this.socketTask.onClose(() => { console.log('WebSocket 已关闭'); this.isOpen = false; this.reconnect(); }); this.socketTask.onError((err) => { console.error('WebSocket 错误', err); this.isOpen = false; }); } // 发送消息 send(msgObj) { if (!this.isOpen) { console.error('连接未建立,消息发送失败'); return; } this.socketTask.send({ data: JSON.stringify(msgObj), success: () => { console.log('消息已发出', msgObj); } }); } // 心跳机制 startHeartbeat() { this.timer = setInterval(() => { if (this.isOpen) { this.send({ type: 'heartbeat', msg: 'ping' }); } }, 30000); } // 监听消息 onMessage(callback) { this.onMessageCallback = callback; } // 断线重连 reconnect() { if (this.reconnectCount < this.maxReconnect) { this.reconnectCount++; setTimeout(() => { console.log(`正在进行第 ${this.reconnectCount} 次重连...`); this.connect(); }, 3000 * this.reconnectCount); } } close() { if (this.socketTask) { this.socketTask.close(); clearInterval(this.timer); } } } export default new ChatSocket('wss://your-api.com/ws/chat');