Pola Heartbeat dan Pemulihan Otomatis Koneksi WebSocket Client-Side
Intisari Solusi:
Menerapkan ping/pong interval dengan timer watchdog dan algoritma exponential backoff memastikan koneksi socket yang terputus di jaringan seluler otomatis pulih tanpa freeze.
class RobustWebSocket {
private ws: WebSocket | null = null;
private retryCount = 0;
connect(url: string) {
this.ws = new WebSocket(url);
this.ws.onclose = () => {
const delay = Math.min(1000 * Math.pow(2, this.retryCount), 30000);
this.retryCount++;
setTimeout(() => this.connect(url), delay);
};
this.ws.onopen = () => { this.retryCount = 0; };
}
}