生产监控前端
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.

143 lines
3.8 KiB

2 years ago
/**
* Author: Fu Guobin
* Date: 2022/08/02
2 years ago
* Last Modified by: Fu Guobin
* Last Modified time: 2023/09/15
2 years ago
* Copyright:Daniel(Fu Guobin)
* Description:websocket方法封装
2 years ago
*/
import mitt from '@/plugins/bus';
class WebSocketService {
url: string;
2 years ago
websocket: WebSocket | null;
isInitialized: boolean;
isConnected: boolean;
heartbeatInterval: number;
reconnectInterval: number;
maxReconnectAttempts: number;
reconnectAttempts: number;
2 years ago
data: any;
constructor() {
this.url = '';
2 years 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;
2 years ago
this.data = null;
}
initialize(url: string): void {
//初始化
this.url = url;
2 years 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();
2 years ago
}
onSend(data: any): void {
//发送消息处理
console.log('websocketSend:', JSON.stringify(data));
if (this.isConnected) {
this.websocket?.send(JSON.stringify(data));
}
2 years ago
}
onMessage(event: MessageEvent): void {
//获取消息处理
2 years ago
if (event.data != '连接成功') {
const response = JSON.parse(event.data);
console.log('response:', response);
2 years 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);
} else if (response.code === 'respMsg') {
console.log(response.msg);
}
2 years 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);
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;
2 years ago
}
}
close(): void {
this.websocket?.close();
}
}
const webSocketService = new WebSocketService();
export default webSocketService;