import { io } from 'socket.io-client' import vcControl from './vcControl' class ExchangeClient { socket: any started = false handlerMap: any = {} loading: any constructor() {} connect(connectedHandler: any, lostConnectionHandler: any, connectFailedHandler: any) { this.socket = io('http://127.0.0.1:3001', { transports: ['websocket'], // 指定传输方式,如WebSocket autoConnect: true, // 是否自动连接 reconnection: true, // 是否自动重新连接 reconnectionAttempts: 5, // 重新连接尝试次数 reconnectionDelay: 1000 // 重新连接延迟时间(毫秒) }) this.socket.on('message', (type: string, ...args: any) => { // 处理接收到的数据 try { this.handlerMap[type] && this.handlerMap[type](...args) } catch (e) { console.error('message', 'topic', e) } }) this.socket.on('disconnect', (reason: any) => { console.error(`Disconnected: ${reason}`) lostConnectionHandler() }) this.socket.on('connect', () => { console.log(`connected`) connectedHandler() if (this.started) { this.joinExchangeCenter() } }) this.socket.on('reconnect_failed', (reason: any) => { console.error('Reconnect failed after maximum attempts') lostConnectionHandler() }) this.socket.on('reconnect', (attemptNumber: number) => { console.log(`Reconnected after ${attemptNumber} attempts`) connectedHandler() if (this.started) { this.joinExchangeCenter() } }) } joinExchangeCenter() { this.socket.emit('call', 'exchange-center.join', { port: vcControl.resource.server, mqttPort: vcControl.resource.mqtt, deviceId: vcControl.deviceId }) this.started = true } leaveExchangeCenter() { this.started = false this.socket.emit('call', 'exchange-center.leave', { port: vcControl.resource.server, mqttPort: vcControl.resource.mqtt, deviceId: vcControl.deviceId }) } subscribe(topic: string, handler: any) { this.handlerMap[topic] = handler if (!this.started) { this.joinExchangeCenter() } } unsubscribe(topic: any) { this.handlerMap[topic] = undefined } disconnect() { this.leaveExchangeCenter() this.handlerMap = {} this.socket.close() } } const exClient = new ExchangeClient() export default exClient