生产监控前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
3.0 KiB

1 year ago
/**
* Author: Fu Guobin
* Date: 2022/08/02
1 year ago
* Last Modified by: Fu Guobin
* Last Modified time: 2023/09/15
1 year ago
* Copyright:Daniel(Fu Guobin)
* Description:websocket方法封装
1 year ago
*/
import mitt from '@/plugins/bus';
class WebSocketService {
url: string;
1 year ago
websocket: WebSocket | null;
isInitialized: boolean;
isConnected: boolean;
heartbeatInterval: number;
reconnectInterval: number;
maxReconnectAttempts: number;
reconnectAttempts: number;
1 year ago
data: any;
constructor() {
this.url = '';
1 year ago
this.websocket = null;
this.isInitialized = false;
this.isConnected = false; //握手
this.heartbeatInterval = 30000; // 默认心跳30秒
this.reconnectInterval = 5000; // 默认重连5秒
this.maxReconnectAttempts = 5; // 默认尝试重连5次
this.reconnectAttempts = 0;
1 year ago
this.data = null;
}
initialize(url: string): void {
//初始化
this.url = url;
1 year ago
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();
1 year ago
}
onSend(data: any): void {
//发送消息处理
console.log('websocketSend:', JSON.stringify(data));
if (this.isConnected) {
this.websocket?.send(JSON.stringify(data));
}
1 year ago
}
onMessage(event: MessageEvent): void {
//获取消息处理
1 year ago
if (event.data != '连接成功') {
const response = JSON.parse(event.data);
console.log('response:', response);
1 year ago
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);
}
1 year ago
}
}
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);
// 错误处理的逻辑
}
startHeartbeat() {
// 发送心跳
this.heartbeatInterval = setInterval(() => {
if (this.websocket?.readyState === WebSocket.OPEN) {
this.websocket.send('ping'); //心跳消息
}
}, this.heartbeatInterval);
}
stopHeartbeat() {
// 停止心跳
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = 0;
1 year ago
}
}
close(): void {
this.websocket?.close();
}
}
const webSocketService = new WebSocketService();
export default webSocketService;