| | |
| | | import { WEBSOCKET_BASE_URL } from '@/config/setting' |
| | | 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 10 seconds |
| | | } |
| | | |
| | | connect() { |
| | |
| | | |
| | | this.webSocket.onopen = (event) => { |
| | | console.log('websocket connection opened.'); |
| | | // 连接成功后可以发送消息 |
| | | // this.sendMessage('Hello Server!'); |
| | | // Start the heartbeat |
| | | this.startHeartbeat(); |
| | | }; |
| | | |
| | | this.webSocket.onmessage = (event) => { |
| | |
| | | |
| | | this.webSocket.onclose = (event) => { |
| | | console.log('websocket connection closed!'); |
| | | // Clear the heartbeat |
| | | this.stopHeartbeat(); |
| | | this.reconnect(); |
| | | }; |
| | | } |
| | | |
| | | sendMessage(message) { |
| | | if (this.webSocket.readyState === WebSocket.OPEN) { |
| | | if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) { |
| | | this.webSocket.send(message); |
| | | } else { |
| | | console.error('WebSocketClient: Cannot send message, WebSocket connection is not open.'); |
| | |
| | | } |
| | | |
| | | close() { |
| | | if (this.webSocket.readyState === WebSocket.OPEN) { |
| | | if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) { |
| | | this.webSocket.close(); |
| | | } |
| | | } |
| | |
| | | }, 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; |
| | | } |
| | | } |
| | | } |