refactor(wsService): improve WebSocket connection handling and logging
All checks were successful
Frontend CI / build-and-push-web (push) Successful in 5m51s
Frontend CI / ota-android (push) Successful in 16m58s
Frontend CI / build-android-apk (push) Successful in 1h20m19s

- Updated getWSUrl method to accept a token parameter for better flexibility.
- Enhanced connection logic with additional logging for connection status and errors.
- Improved error handling during connection attempts and disconnections.
- Added checks to prevent duplicate handling of disconnections.
- Refactored reconnect logic to provide clearer feedback on reconnection attempts.
This commit is contained in:
lafay
2026-03-26 22:05:07 +08:00
parent ba99900624
commit db7885086f

View File

@@ -208,27 +208,35 @@ class WebSocketService {
private isFallbackMode = false; private isFallbackMode = false;
private fallbackCheckTimer: NodeJS.Timeout | null = null; private fallbackCheckTimer: NodeJS.Timeout | null = null;
private getWSUrl(): string { private getWSUrl(token: string | null): string {
const token = api.getToken();
return `${WS_URL}?token=${encodeURIComponent(token || '')}`; return `${WS_URL}?token=${encodeURIComponent(token || '')}`;
} }
async connect(): Promise<boolean> { async connect(): Promise<boolean> {
this.shouldRun = true; 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; this.isConnecting = true;
console.log('[WebSocket] Connecting...');
try { try {
const token = await api.getToken(); const token = await api.getToken();
if (!token) { if (!token) {
console.error('[WebSocket] No token available');
this.isConnecting = false; this.isConnecting = false;
this.scheduleReconnect();
return false; 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 = new WebSocket(url);
this.ws.onopen = () => { this.ws.onopen = () => {
console.log('[WebSocket] Connected successfully');
this.isConnecting = false; this.isConnecting = false;
this.connected = true; this.connected = true;
this.reconnectAttempts = 0; this.reconnectAttempts = 0;
@@ -246,16 +254,18 @@ class WebSocketService {
this.handleIncoming(event.data); this.handleIncoming(event.data);
}; };
this.ws.onerror = () => { this.ws.onerror = (error) => {
this.handleDisconnected(); console.error('[WebSocket] Error:', error);
}; };
this.ws.onclose = () => { this.ws.onclose = (event) => {
console.log('[WebSocket] Closed:', event.code, event.reason);
this.handleDisconnected(); this.handleDisconnected();
}; };
return true; return true;
} catch { } catch (error) {
console.error('[WebSocket] Connection error:', error);
this.isConnecting = false; this.isConnecting = false;
this.scheduleReconnect(); this.scheduleReconnect();
return false; return false;
@@ -655,6 +665,7 @@ class WebSocketService {
} }
this.stopReconnect(); this.stopReconnect();
console.log(`[WebSocket] Reconnecting in ${this.reconnectDelay}ms (attempt ${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`);
this.reconnectTimer = setTimeout(() => { this.reconnectTimer = setTimeout(() => {
this.reconnectAttempts += 1; this.reconnectAttempts += 1;
this.connect(); this.connect();
@@ -783,6 +794,14 @@ class WebSocketService {
} }
private handleDisconnected(): void { 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; const wasActive = this.connected || this.ws != null || this.isConnecting;
this.isConnecting = false; this.isConnecting = false;
this.connected = false; this.connected = false;
@@ -800,6 +819,8 @@ class WebSocketService {
if (this.shouldRun) { if (this.shouldRun) {
this.scheduleReconnect(); this.scheduleReconnect();
} else {
console.log('[WebSocket] shouldRun is false, not reconnecting');
} }
} }
} }