diff --git a/src/services/wsService.ts b/src/services/wsService.ts index 3cecee4..edca371 100644 --- a/src/services/wsService.ts +++ b/src/services/wsService.ts @@ -208,27 +208,35 @@ class WebSocketService { private isFallbackMode = false; private fallbackCheckTimer: NodeJS.Timeout | null = null; - private getWSUrl(): string { - const token = api.getToken(); + private getWSUrl(token: string | null): string { return `${WS_URL}?token=${encodeURIComponent(token || '')}`; } async connect(): Promise { this.shouldRun = true; - if (this.isConnecting || this.isConnected()) return true; + if (this.isConnecting || this.isConnected()) { + console.log('[WebSocket] Already connected or connecting'); + return true; + } this.isConnecting = true; + console.log('[WebSocket] Connecting...'); try { const token = await api.getToken(); if (!token) { + console.error('[WebSocket] No token available'); this.isConnecting = false; + this.scheduleReconnect(); return false; } - const url = this.getWSUrl(); + const url = this.getWSUrl(token); + console.log('[WebSocket] Connecting to:', url.replace(token, '***')); + this.ws = new WebSocket(url); this.ws.onopen = () => { + console.log('[WebSocket] Connected successfully'); this.isConnecting = false; this.connected = true; this.reconnectAttempts = 0; @@ -246,16 +254,18 @@ class WebSocketService { this.handleIncoming(event.data); }; - this.ws.onerror = () => { - this.handleDisconnected(); + this.ws.onerror = (error) => { + console.error('[WebSocket] Error:', error); }; - this.ws.onclose = () => { + this.ws.onclose = (event) => { + console.log('[WebSocket] Closed:', event.code, event.reason); this.handleDisconnected(); }; return true; - } catch { + } catch (error) { + console.error('[WebSocket] Connection error:', error); this.isConnecting = false; this.scheduleReconnect(); return false; @@ -655,6 +665,7 @@ class WebSocketService { } this.stopReconnect(); + console.log(`[WebSocket] Reconnecting in ${this.reconnectDelay}ms (attempt ${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`); this.reconnectTimer = setTimeout(() => { this.reconnectAttempts += 1; this.connect(); @@ -783,6 +794,14 @@ class WebSocketService { } private handleDisconnected(): void { + // 防止重复调用 + if (!this.connected && !this.ws && !this.isConnecting) { + console.log('[WebSocket] Already disconnected, ignoring'); + return; + } + + console.log('[WebSocket] Handling disconnect...'); + const wasActive = this.connected || this.ws != null || this.isConnecting; this.isConnecting = false; this.connected = false; @@ -800,6 +819,8 @@ class WebSocketService { if (this.shouldRun) { this.scheduleReconnect(); + } else { + console.log('[WebSocket] shouldRun is false, not reconnecting'); } } }