/* * @Author: zhp * @Date: 2024-03-26 14:38:14 * @LastEditTime: 2024-03-26 15:45:20 * @LastEditors: zhp * @Description: */ class WebSocketHeartbeat { constructor(url) { this.url = url; this.ws = null; this.heartBeatTimer = null; this.isReconnecting = false; this.initWebSocket(); } initWebSocket() { this.ws = new WebSocket(this.url); this.ws.onopen = () => { console.log('WebSocket连接已打开'); this.startHeartBeat(); }; this.ws.onmessage = (event) => { console.log('收到消息:', event.data); // 在这里处理收到的消息,可以根据具体需求进行处理 }; this.ws.onclose = () => { console.log('WebSocket连接已关闭'); this.stopHeartBeat(); if (!this.isReconnecting) { this.reconnectWebSocket(); } }; } startHeartBeat() { this.heartBeatTimer = setInterval(() => { if (this.ws.readyState === WebSocket.OPEN) { // this.ws.send('ping'); } }, 5000); } stopHeartBeat() { clearInterval(this.heartBeatTimer); } reconnectWebSocket() { this.isReconnecting = true; setTimeout(() => { this.initWebSocket(); this.isReconnecting = false; }, 3000); } closeWebSocket() { this.ws.close(); } } export default WebSocketHeartbeat;