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