export default class WebSocketService { constructor(url) { this.socket = null; this.url = url; // 心跳定时器 this.heartbeatTimer = null; this.heartbeatInterval = 30000; // 30秒 // 重连次数 this.reconnectAttempts = 50; // 默认重连次数 this.maxReconnectAttempts = 100; // 最大重连次数 this.reconnectInterval = 2000; // 2秒 // 存储回调函数 this.onMessageCallback = null; // 存储回调函数 } // 重连 reconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`); setTimeout(() => { this.connect(); }, this.reconnectInterval); } else { console.error('达到最大重连次数,连接失败'); } } // 开启心跳 startHeartbeat() { this.heartbeatTimer = setInterval(() => { this.send({ type: 'heartbeat' }); }, this.heartbeatInterval); } // 关闭心跳 stopHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } // 连接 async connect() { this.socket = new WebSocket(this.url); this.socket.onopen = await this.onOpen.bind(this); this.socket.onmessage = this.onMessage.bind(this); this.socket.onclose = this.onClose.bind(this); this.socket.onerror = this.onError.bind(this); } // 连接成功 onOpen() { console.log('WebSocket连接已建立'); this.reconnectAttempts = 0; this.startHeartbeat(); } // onMessage(event) { console.log('收到消息:', event.data); if (this.onMessageCallback) { this.onMessageCallback(event.data); // 调用回调函数 } } // 接收到错误消息 onClose() { console.log('WebSocket连接已关闭'); this.stopHeartbeat(); this.reconnect(); } // 接收到错误消息 onError(error) { console.error('WebSocket错误:', error); } // 发送消息 send(data) { if (this.socket && this.socket.readyState === WebSocket.OPEN) { this.socket.send(JSON.stringify(data)); } else { console.error('WebSocket未连接'); } } // 关闭连接 close() { if (this.socket) { this.socket.close(); } } } // urls: [ // 'turn:124.71.68.142:3478?transport=udp', // 强制UDP // 'turn:124.71.68.142:3478?transport=tcp' // TCP备用 // ] // const ws = new WebSocketService(`ws://192.168.0.59:3001/ws?user_id=${userId}`)