import { CommonUtils } from "@/utils/common.js"; class WebSocketServices { constructor() { this.wsInstance = null; // WebSocket 实例 this.isConnecting = false; // 避免并发重连 this.isConnected = false; // 避免并发重连 this.wsUrl = CommonUtils.httpFormatWs() } // 建立WebSocket连接 createConnect(userId) { // 使用用户标识 作为后端连接的凭据 if(this.isConnecting || !userId || this.isConnected) { return } console.log('wsUrl: ',this.wsUrl); console.log('userId: ',userId); this.wsInstance = uni.connectSocket({ url: this.wsUrl, header: { "X-User-Id": userId }, success() { this.isConnecting = true } }) // 监听套接字连接建立 uni.onSocketOpen((res) => { console.log('[webSocket]: 套接字连接建立成功'); this.isConnecting = false this.isConnected = true console.log('res: ',res); this.wsInstance = res.socketTask }) } // 重连 reConnect(reCount = 1, limit = 3) { if(reCount > limit) { uni.showToast({ icon: 'none', title: `超出最大重连次数。已退出连接` }) this.isConnecting = false return } uni.showToast({ icon: 'none', title: `正在尝试重连,重连次数 ${reCount}` }) reConnect(reCount+1, limit) uni.hideToast() } // 连接注销 disConnect() { } } export default new WebSocketServices()