| | |
| | | private socketTask: Taro.SocketTask | null = null; |
| | | private url: string = ''; |
| | | private isConnected: boolean = false; |
| | | private isConnecting: boolean = false; |
| | | private isManualClose: boolean = false; |
| | | private reconnectAttempts: number = 0; |
| | | private maxReconnectAttempts: number = 5; |
| | | private reconnectTimer: any = null; |
| | |
| | | * @param url WebSocket地址 |
| | | */ |
| | | public async connect(url: string) { |
| | | if (this.socketTask || this.isConnected) { |
| | | if (this.socketTask || this.isConnected || this.isConnecting) { |
| | | console.log('WebSocket 已连接或正在连接中'); |
| | | return; |
| | | } |
| | | |
| | | this.url = url; |
| | | this.isConnecting = true; |
| | | this.isManualClose = false; |
| | | console.log(`正在连接 WebSocket: ${url}`); |
| | | |
| | | const uid = await getStorage(_UID) || '-1'; |
| | |
| | | success: () => { }, |
| | | fail: (err) => { |
| | | console.error('WebSocket 连接失败:', err); |
| | | this.isConnecting = false; |
| | | this.handleReconnect(); |
| | | } |
| | | }); |
| | | const maybeTask: any = task as any; |
| | | if (maybeTask && typeof maybeTask.onOpen === 'function') { |
| | | this.socketTask = maybeTask; |
| | | this.isConnecting = false; |
| | | this.initEventListeners(); |
| | | return; |
| | | } |
| | |
| | | maybeTask |
| | | .then((resolvedTask) => { |
| | | this.socketTask = resolvedTask; |
| | | this.isConnecting = false; |
| | | this.initEventListeners(); |
| | | }) |
| | | .catch((err) => { |
| | | console.error('WebSocket 连接失败:', err); |
| | | this.isConnecting = false; |
| | | this.handleReconnect(); |
| | | }); |
| | | return; |
| | | } |
| | | this.socketTask = null; |
| | | this.isConnecting = false; |
| | | this.initEventListeners(); |
| | | } |
| | | |
| | |
| | | this.stopHeartbeat(); |
| | | this.socketTask = null; |
| | | |
| | | if (res.code !== 1000) { |
| | | if (!this.isManualClose) { |
| | | this.handleReconnect(); |
| | | } |
| | | this.notifyListeners('close', res); |
| | |
| | | this.stopHeartbeat(); |
| | | this.socketTask = null; |
| | | |
| | | if (res.code !== 1000) { |
| | | if (!this.isManualClose) { |
| | | this.handleReconnect(); |
| | | } |
| | | this.notifyListeners('close', res); |
| | |
| | | * 关闭连接 |
| | | */ |
| | | public close() { |
| | | this.isManualClose = true; |
| | | this.stopHeartbeat(); |
| | | if (this.reconnectTimer) { |
| | | clearTimeout(this.reconnectTimer); |
| | |
| | | this.socketTask = null; |
| | | } |
| | | this.isConnected = false; |
| | | this.isConnecting = false; |
| | | } |
| | | |
| | | /** |