// websocket.js class WebSocketClient { constructor(url) { this.currentUrl = url; this.socket = null; this.heartbeatInterval = null; this.messageCallback = null; this.reconnectTimer = null; this.reconnectAttempts = 0; this.MAX_RECONNECT_ATTEMPTS = 5; this.RECONNECT_DELAY = 5000; // 5 秒 this.HEARTBEAT_INTERVAL = 30000; // 30 秒 this.URL_CHECK_INTERVAL = 5000; // 每 5 秒检查一次 URL this.init(); this.startUrlCheck(); } init() { try { console.log('尝试创建 WebSocket 连接:', this.currentUrl); this.socket = new WebSocket(this.currentUrl); this.socket.onopen = () => { console.log('WebSocket 连接已建立:', this.currentUrl); this.startHeartbeat(); this.reconnectAttempts = 0; }; this.socket.onmessage = (event) => { if (this.messageCallback) { this.messageCallback(event.data); } }; this.socket.onclose = () => { console.log('WebSocket 连接已关闭:', this.currentUrl); this.stopHeartbeat(); this.reconnect(); }; this.socket.onerror = (error) => { console.error('WebSocket 发生错误:', error); this.socket.close(); }; } catch (error) { console.error('创建 WebSocket 连接时出错:', error); } } startHeartbeat() { this.heartbeatInterval = setInterval(() => { if (this.socket && this.socket.readyState === WebSocket.OPEN) { this.socket.send('ping'); } }, this.HEARTBEAT_INTERVAL); } stopHeartbeat() { if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); this.heartbeatInterval = null; } } onMessage(callback) { this.messageCallback = callback; } send(message) { if (this.socket && this.socket.readyState === WebSocket.OPEN) { this.socket.send(message); } else { console.error('WebSocket 连接未打开,无法发送消息'); } } disconnect() { if (this.socket) { this.stopHeartbeat(); this.socket.close(); this.socket = null; } } reconnect() { if (this.reconnectAttempts < this.MAX_RECONNECT_ATTEMPTS) { this.reconnectTimer = setTimeout(() => { console.log('尝试重新连接...', this.currentUrl); this.reconnectAttempts++; this.init(); }, this.RECONNECT_DELAY); } else { console.error('达到最大重连次数,停止重连'); } } startUrlCheck() { setInterval(() => { const newUrl = this.getUpdatedUrl(); if (newUrl && newUrl!== this.currentUrl) { this.disconnect(); this.currentUrl = newUrl; this.init(); } }, this.URL_CHECK_INTERVAL); } // 这个方法需要根据实际情况重写,用于获取最新的 URL getUpdatedUrl() { // 这里只是示例,返回 null 表示没有更新的 URL return null; } } export default WebSocketClient;