/** * Author: Fu Guobin * Date: 2022/08/02 * Last Modified by: Fu Guobin * Last Modified time: 2023/09/15 * Copyright:Daniel(Fu Guobin) * Description:websocket方法封装 */ import mitt from '@/plugins/bus'; class WebSocketService { url: string; websocket: WebSocket | null; isInitialized: boolean; isConnected: boolean; heartbeatInterval: number; reconnectInterval: number; maxReconnectAttempts: number; reconnectAttempts: number; data: any; constructor() { this.url = ''; this.websocket = null; this.isInitialized = false; this.isConnected = false; //握手 this.heartbeatInterval = 30000; // 默认心跳30秒 this.reconnectInterval = 5000; // 默认重连5秒 this.maxReconnectAttempts = 5; // 默认尝试重连5次 this.reconnectAttempts = 0; this.data = null; } initialize(url: string): void { //初始化 this.url = url; this.websocket = new WebSocket(url); this.websocket.onopen = this.onOpen.bind(this); this.websocket.onclose = this.onClose.bind(this); this.websocket.onerror = this.onError.bind(this); this.websocket.onmessage = this.onMessage.bind(this); this.isInitialized = true; } onOpen(): void { this.isConnected = true; // 进行握手操作,如果需要的话 this.reconnectAttempts = 0; // 重置重连次数 this.startHeartbeat(); } onSend(data: any): void { //发送消息处理 console.log('websocketSend:', JSON.stringify(data)); if (this.isConnected) { this.websocket?.send(JSON.stringify(data)); } } onMessage(event: MessageEvent): void { //获取消息处理 if (event.data != '连接成功') { const response = JSON.parse(event.data); console.log('response:', response); this.data = response; // 处理返回的数据 if (response.code === 'datareal') { console.log('table'); mitt.emit('tableMessage', response); } else if (response.code === 'alertDev') { console.log('waring'); mitt.emit('waringMessage', response); } else if (response.code === 'respMsg') { console.log(response.msg); } } } onClose(): void { // 关闭WebSocket连接的处理逻辑 this.isConnected = false; this.stopHeartbeat(); if (this.reconnectAttempts < this.maxReconnectAttempts) { setTimeout(() => { this.reconnectAttempts++; this.initialize(this.url); }, this.reconnectInterval); } } onError(error: Event): void { console.error('WebSocket error:', error); ElMessageBox.confirm('WebSocket连接错误,是否重连?', '提示', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }) .then(() => { this.initialize(this.url); }) .catch(() => { ElMessage({ type: 'info', message: '您已取消!' }); }); // 错误处理的逻辑 } startHeartbeat() { // 发送心跳 this.heartbeatInterval = setInterval(() => { if (this.websocket?.readyState === WebSocket.OPEN) { const userStorageInfo = sessionStorage.getItem('userInfo'); const userInfo = JSON.parse(userStorageInfo === null ? '' : userStorageInfo); const hearData = { code: 'heart', data: { username: userInfo.userName } }; console.log(hearData) this.websocket.send(JSON.stringify(hearData)); //心跳消息 } }, this.heartbeatInterval); } stopHeartbeat() { // 停止心跳 if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); this.heartbeatInterval = 0; } } close(): void { this.websocket?.close(); } } const webSocketService = new WebSocketService(); export default webSocketService;