#
luxiaotao1123
2024-04-03 bf18e7de3ebfa4d258b1b4c94451a2221a17cd42
zy-asrs-flow/src/pages/map/websocket.js
@@ -1,10 +1,12 @@
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() {
@@ -17,8 +19,8 @@
        this.webSocket.onopen = (event) => {
            console.log('websocket connection opened.');
            // 连接成功后可以发送消息
            // this.sendMessage('Hello Server!');
            // Start the heartbeat
            this.startHeartbeat();
        };
        this.webSocket.onmessage = (event) => {
@@ -32,12 +34,14 @@
        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.');
@@ -50,7 +54,7 @@
    }
    close() {
        if (this.webSocket.readyState === WebSocket.OPEN) {
        if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
            this.webSocket.close();
        }
    }
@@ -62,4 +66,19 @@
        }, 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;
        }
    }
}