| import { WEBSOCKET_BASE_URL } from '@/config/setting'; | 
|   | 
| export default class WebSocketClient { | 
|   | 
|     constructor(path) { | 
|         this.url = WEBSOCKET_BASE_URL + path; | 
|         this.webSocket = null; | 
|         this.heartbeatInterval = null; // Store the interval ID | 
|         this.heartbeatFrequency = 30000; // Heartbeat every 30 seconds | 
|     } | 
|   | 
|     connect() { | 
|         if (!this.url) { | 
|             console.error('WebSocketClient: Cannot connect without url.'); | 
|             return; | 
|         } | 
|   | 
|         this.webSocket = new WebSocket(this.url); | 
|   | 
|         this.webSocket.onopen = (event) => { | 
|             console.log('websocket connection opened.'); | 
|             // Start the heartbeat | 
|             this.startHeartbeat(); | 
|         }; | 
|   | 
|         this.webSocket.onmessage = (event) => { | 
|             // console.log('websocket message received:', event.data); | 
|             this.onMessage(event.data); | 
|         }; | 
|   | 
|         this.webSocket.onerror = (event) => { | 
|             console.error('websocket error observed:', event); | 
|         }; | 
|   | 
|         this.webSocket.onclose = (event) => { | 
|             console.log('websocket connection closed!'); | 
|             // Clear the heartbeat | 
|             this.stopHeartbeat();    | 
|             this.reconnect(); | 
|         }; | 
|     } | 
|   | 
|     sendMessage(message) { | 
|         if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) { | 
|             this.webSocket.send(message); | 
|         } else { | 
|             console.error('WebSocketClient: Cannot send message, WebSocket connection is not open.'); | 
|         } | 
|     } | 
|   | 
|     // Override | 
|     onMessage(data) { | 
|     } | 
|   | 
|     close() { | 
|         if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) { | 
|             this.webSocket.close(); | 
|         } | 
|     } | 
|   | 
|     reconnect() { | 
|         setTimeout(() => { | 
|             console.log('WebSocketClient: Attempting to reconnect...'); | 
|             this.connect(); | 
|         }, 3000); | 
|     } | 
|   | 
|     startHeartbeat() { | 
|         if(this.heartbeatInterval) { | 
|             clearInterval(this.heartbeatInterval); | 
|         } | 
|         this.heartbeatInterval = setInterval(() => { | 
|             this.sendMessage('1'); | 
|         }, this.heartbeatFrequency); | 
|     } | 
|   | 
|     stopHeartbeat() { | 
|         if (this.heartbeatInterval) { | 
|             clearInterval(this.heartbeatInterval); | 
|             this.heartbeatInterval = null; | 
|         } | 
|     } | 
| } |