Chuyển tới nội dung chính

WebSocket Service

Service class managing real-time bidirectional communication with the backend, including automatic reconnection, heartbeat, and message routing.

Overview

The WebSocketService provides:

  • Automatic reconnection with exponential backoff
  • Heartbeat mechanism for connection health
  • Topic-based message routing
  • Connection state management
  • Manual connect/disconnect controls
  • Message handler registration
  • Integration with Zustand store
graph TD
A[WebSocketService] --> B[WebSocket Connection]
A --> C[Reconnection Manager]
A --> D[Heartbeat System]
A --> E[Message Router]

B --> F[ws://localhost:5000]

C --> G[scheduleReconnect]
C --> H[5s Interval]

D --> I[10s Heartbeat]

E --> J[handleMessage]
J --> K[initial]
J --> L[camera_update]
J --> M[weather_update]
J --> N[aqi_update]
J --> O[accident_alert]

K --> P[Traffic Store]
L --> P
M --> P
N --> P
O --> P

Class API

Constructor

class WebSocketService {
private ws: WebSocket | null = null;
private reconnectInterval: number = 5000;
private url: string;

constructor() {
this.url = import.meta.env.VITE_WS_URL || 'ws://localhost:5000';
}
}

connect()

Establish WebSocket connection.

connect(): void

Features:

  • Prevents duplicate connections
  • Sets up event handlers (onopen, onmessage, onerror, onclose)
  • Starts heartbeat on successful connection
  • Updates store connection status

disconnect()

Gracefully close WebSocket connection.

disconnect(): void

Features:

  • Marks as intentional close (prevents reconnection)
  • Clears reconnect timers
  • Stops heartbeat
  • Closes WebSocket

registerHandler()

Register a custom message handler for a specific type.

registerHandler(type: string, handler: (data: any) => void): void

Message Types

TypeDescriptionStore Action
initialInitial data snapshotMultiple setters
camera_updateCamera status changesaddCamera()
weather_updateWeather observationsaddWeather()
aqi_updateAir quality readingsaddAirQuality()
new_accidentNew accident detectedaddAccident()
pattern_changeTraffic pattern updatesaddPattern()
accident_alertHigh-priority accidentNotification
aqi_warningHigh AQI warningNotification

Connection Lifecycle

stateDiagram-v2
[*] --> Disconnected
Disconnected --> Connecting: connect()
Connecting --> Connected: onopen
Connecting --> Disconnected: onerror
Connected --> Disconnected: onclose
Disconnected --> Connecting: scheduleReconnect
Connected --> [*]: disconnect()

Usage

import { wsService } from './services/websocket';

// In Dashboard component
useEffect(() => {
wsService.connect();
return () => wsService.disconnect();
}, []);

// Register custom handler
wsService.registerHandler('custom_event', (data) => {
console.log('Custom event received:', data);
});

Singleton Instance

The service exports a singleton instance:

export const wsService = new WebSocketService();

Message Handling

private handleMessage(message: WebSocketMessage): void {
const store = useTrafficStore.getState();

switch (message.type) {
case 'initial':
if (message.data?.cameras) {
message.data.cameras.forEach(store.addCamera);
}
// ... other data types
break;

case 'camera_update':
if (Array.isArray(message.data)) {
message.data.forEach(store.addCamera);
}
break;

// ... more cases
}
}

Configuration

SettingDefaultDescription
urlws://localhost:5000WebSocket server URL
reconnectInterval5000Reconnection delay (ms)
heartbeatInterval10000Heartbeat ping interval (ms)

Dependencies

  • Native WebSocket API
  • useTrafficStore: Zustand store for state updates
  • WebSocketMessage type from ../types

Error Handling

  • Connection errors trigger automatic reconnection
  • Message parse errors are logged but don't crash
  • Graceful handling of server disconnections

See Also