#
luxiaotao1123
2024-06-11 bd6f16c7a6695606d7ebb5baa56eefe65b603cf2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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;
        }
    }
}