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

82 lines
2.0 KiB

1 year ago
/**
* Author: Fu Guobin
* Date: 2022/08/02
1 year ago
* Last Modified by: Fu Guobin
* Last Modified time: 2023/08/28
* Copyright:Daniel(Fu Guobin)
* Description:websocket函数封装
*/
import { reactive, toRefs } from 'vue';
import { tableStore } from '@/store/modules/table';
import mitt from '@/plugins/bus';
// const tableStoreCounter = tableStore();
class WebSocketService {
websocket: WebSocket | null;
isInitialized: boolean;
isConnected: boolean;
data: any;
constructor() {
this.websocket = null;
this.isInitialized = false;
this.isConnected = false;
this.data = null;
}
initialize(url: string): void {
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;
// 进行握手操作,如果需要的话
}
onClose(): void {
this.isConnected = false;
// 关闭WebSocket连接的处理逻辑
}
onError(error: Event): void {
console.error('WebSocket error:', error);
// 错误处理的逻辑
}
onMessage(event: MessageEvent): void {
if (event.data != '连接成功') {
const response = JSON.parse(event.data);
console.log(response);
this.data = response;
// 处理返回的数据
mitt.emit('tableMessage', response);
// const oldData = tableStoreCounter.tableDataStore;
// const index = oldData.findIndex((obj) => obj.id === response.id);
// if (index !== -1) {
// oldData.splice(index, 1, response);
// }
// tableStoreCounter.tableDataAction(oldData);
}
}
send(data: any): void {
console.log('websocketSend:', JSON.stringify(data));
if (this.isConnected) {
this.websocket?.send(JSON.stringify(data));
}
}
close(): void {
this.websocket?.close();
}
}
const webSocketService = new WebSocketService();
export default webSocketService;