Browse Source

优化

develop
fuguobin 1 year ago
parent
commit
d5c9cd72b9
  1. 103
      src/utils/socket.ts
  2. 3
      src/views/monitoring/components/header.vue
  3. 10
      src/views/monitoring/components/menu.vue
  4. 21
      src/views/monitoring/screen/index.vue

103
src/utils/socket.ts

@ -2,10 +2,11 @@
* Author: Fu Guobin * Author: Fu Guobin
* Date: 2022/08/02 * Date: 2022/08/02
* Last Modified by: Fu Guobin * Last Modified by: Fu Guobin
* Last Modified time: 2023/09/15 * Last Modified time: 2023/09/21
* Copyright:Daniel(Fu Guobin) * Copyright:Daniel(Fu Guobin)
* Description:websocket方法封装 * Description:websocket方法封装
*/ */
import type { Action } from 'element-plus';
import mitt from '@/plugins/bus'; import mitt from '@/plugins/bus';
class WebSocketService { class WebSocketService {
@ -13,6 +14,7 @@ class WebSocketService {
websocket: WebSocket | null; websocket: WebSocket | null;
isInitialized: boolean; isInitialized: boolean;
isConnected: boolean; isConnected: boolean;
heartTimer: number | null;
heartbeatInterval: number; heartbeatInterval: number;
reconnectInterval: number; reconnectInterval: number;
maxReconnectAttempts: number; maxReconnectAttempts: number;
@ -23,18 +25,25 @@ class WebSocketService {
this.url = ''; this.url = '';
this.websocket = null; this.websocket = null;
this.isInitialized = false; this.isInitialized = false;
this.isConnected = false; //握手 this.isConnected = false; //连接状态
this.heartTimer = null; //心跳计时
this.heartbeatInterval = 30000; // 默认心跳30秒 this.heartbeatInterval = 30000; // 默认心跳30秒
this.reconnectInterval = 5000; // 默认重连5 this.reconnectInterval = 10000; // 默认重连10
this.maxReconnectAttempts = 5; // 默认尝试重连5次 this.maxReconnectAttempts = 5; // 默认尝试重连5次
this.reconnectAttempts = 0; this.reconnectAttempts = 0; //重连次数
this.data = null; this.data = null;
} }
initialize(url: string): void { initialize(url: string): void {
//初始化 //初始化
console.log('websocket初始化');
this.url = url; this.url = url;
this.websocket = new WebSocket(url); this.websocket = new WebSocket(url);
console.log('readyState1--', this.websocket?.readyState);
this.websocket.onopen = e => {
console.log('readyState--', this.websocket?.readyState);
console.log('websocket onopen--', e);
};
this.websocket.onopen = this.onOpen.bind(this); this.websocket.onopen = this.onOpen.bind(this);
this.websocket.onclose = this.onClose.bind(this); this.websocket.onclose = this.onClose.bind(this);
this.websocket.onerror = this.onError.bind(this); this.websocket.onerror = this.onError.bind(this);
@ -43,7 +52,9 @@ class WebSocketService {
} }
onOpen(): void { onOpen(): void {
this.isConnected = true; // 进行握手操作,如果需要的话 console.log('readyState2--', this.websocket?.readyState);
console.log('websocket onOpen');
this.isConnected = true; // 连接状态
this.reconnectAttempts = 0; // 重置重连次数 this.reconnectAttempts = 0; // 重置重连次数
this.startHeartbeat(); this.startHeartbeat();
} }
@ -70,6 +81,18 @@ class WebSocketService {
console.log('waring'); console.log('waring');
mitt.emit('waringMessage', response); mitt.emit('waringMessage', response);
} else if (response.code === 'respMsg') { } else if (response.code === 'respMsg') {
if (response.data[0].code === -1 || response.data[0].code === 1) {
this.close(false);
ElMessageBox.alert(response.msg, '提示', {
// if you want to disable its autofocus
// autofocus: false,
confirmButtonText: 'OK',
callback: (action: Action) => {
localStorage.clear();
window.location.href = '/';
}
});
}
console.log(response.msg); console.log(response.msg);
} }
} }
@ -77,38 +100,49 @@ class WebSocketService {
onClose(): void { onClose(): void {
// 关闭WebSocket连接的处理逻辑 // 关闭WebSocket连接的处理逻辑
this.isConnected = false; console.log('websocket关闭');
this.stopHeartbeat(); // this.isInitialized = status === false ? false : true;
this.isConnected = false; //关闭连接
this.stopHeartbeat(); //关闭心跳
if (this.isInitialized) {
console.log('WebSocke尝试重连1');
this.tryReconnect();
}
}
onError(error: Event): void {
// 错误处理的逻辑
console.error('WebSocket连接错误:', error);
ElNotification({
message: 'webSocket连接发生错误,正在尝试重连…',
type: 'error'
});
this.isConnected = false; //关闭连接
this.stopHeartbeat(); //关闭心跳
if (this.isInitialized) {
console.log('WebSocke尝试重连2');
this.tryReconnect();
}
}
tryReconnect() {
//尝试重连
console.log('WebSocket尝试重连:', this.reconnectAttempts);
if (this.reconnectAttempts < this.maxReconnectAttempts) { if (this.reconnectAttempts < this.maxReconnectAttempts) {
setTimeout(() => { setTimeout(() => {
this.reconnectAttempts++; this.reconnectAttempts++;
this.initialize(this.url); this.initialize(this.url);
}, this.reconnectInterval); }, this.reconnectInterval);
} else {
this.close(false);
} }
} }
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() { startHeartbeat() {
// 发送心跳 // 发送心跳
this.heartbeatInterval = setInterval(() => { console.log('websocket发送心跳');
this.heartTimer = setInterval(() => {
console.log('websocket心跳计时--', this.heartTimer);
if (this.websocket?.readyState === WebSocket.OPEN) { if (this.websocket?.readyState === WebSocket.OPEN) {
const userStorageInfo = sessionStorage.getItem('userInfo'); const userStorageInfo = sessionStorage.getItem('userInfo');
const userInfo = JSON.parse(userStorageInfo === null ? '' : userStorageInfo); const userInfo = JSON.parse(userStorageInfo === null ? '' : userStorageInfo);
@ -118,7 +152,7 @@ class WebSocketService {
username: userInfo.userName username: userInfo.userName
} }
}; };
console.log(hearData) console.log(hearData);
this.websocket.send(JSON.stringify(hearData)); //心跳消息 this.websocket.send(JSON.stringify(hearData)); //心跳消息
} }
}, this.heartbeatInterval); }, this.heartbeatInterval);
@ -126,14 +160,19 @@ class WebSocketService {
stopHeartbeat() { stopHeartbeat() {
// 停止心跳 // 停止心跳
if (this.heartbeatInterval) { console.log('websocket停止心跳');
clearInterval(this.heartbeatInterval); if (this.heartTimer != null) {
this.heartbeatInterval = 0; clearInterval(this.heartTimer);
this.heartTimer = null;
} }
console.log('websocket停止心跳--', this.heartTimer);
} }
close(): void { close(status: any): void {
console.log('close--', status);
this.isInitialized = status;
this.websocket?.close(); this.websocket?.close();
console.log('websocket连接已关闭');
} }
} }

3
src/views/monitoring/components/header.vue

@ -281,7 +281,8 @@ function warClose() {
margin: 0 auto; margin: 0 auto;
h3 { h3 {
font-size: 38px; height: 57px;
font-size: 3.8rem;
font-family: 'YouSheBiaoTiHei'; font-family: 'YouSheBiaoTiHei';
font-weight: 400; font-weight: 400;
letter-spacing: 4px; letter-spacing: 4px;

10
src/views/monitoring/components/menu.vue

@ -88,10 +88,11 @@ function removeChildren(menu: any) {
} }
}); });
} }
// function renderMenuLabel(option: MenuOption) {
function renderMenuLabel(option: MenuOption) { const renderMenuLabel = (option: MenuOption) => {
// //
return h(NEllipsis, null, option.deptName as string); // return h(NEllipsis, null, option.deptName as string);
return h(NEllipsis, null, { default: () => option.deptName });
} }
function menuUpdateValue(key: string, item: MenuOption) { function menuUpdateValue(key: string, item: MenuOption) {
@ -258,4 +259,5 @@ function menuUpdateValue(key: string, item: MenuOption) {
.menuCantent::-webkit-scrollbar-corner, .menuCantent::-webkit-scrollbar-corner,
.tableGrid ::-webkit-scrollbar-corner { .tableGrid ::-webkit-scrollbar-corner {
background-color: transparent; background-color: transparent;
}</style> }
</style>

21
src/views/monitoring/screen/index.vue

@ -1,7 +1,8 @@
<template> <template>
<div ref="screenRef" class="screen"> <div ref="screenRef" class="screen">
<section ref="titleRef" class="header"> <section ref="titleRef" class="header">
<Header :titleData="titleData" :settingShow="true" :warningShow="true" @showModalClick="showModalClick" @returnClick="returnClick" /> <Header :titleData="titleData" :settingShow="true" :warningShow="true" @showModalClick="showModalClick"
@returnClick="returnClick" />
<!-- <div class="title"> <!-- <div class="title">
<h3>{{ titleData }}</h3> <h3>{{ titleData }}</h3>
</div> </div>
@ -78,7 +79,7 @@
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import router from '@/router'; import { useRoute, useRouter, onBeforeRouteLeave } from "vue-router";
// import { useDateFormat, useNow } from '@vueuse/core'; // import { useDateFormat, useNow } from '@vueuse/core';
// import { Filter, Maximize, Settings, Power } from '@vicons/tabler'; // import { Filter, Maximize, Settings, Power } from '@vicons/tabler';
import Header from '../components/header.vue'; import Header from '../components/header.vue';
@ -87,7 +88,11 @@ import Main from './components/main.vue';
import InfoPanel from './components/infoPanel.vue'; import InfoPanel from './components/infoPanel.vue';
import ShowTree from './components/showTree.vue'; import ShowTree from './components/showTree.vue';
import useStorage from '@/utils/useStorage' import useStorage from '@/utils/useStorage'
import socket from '@/utils/socket';
const sessionStorageIns = useStorage('sessionStorage'); const sessionStorageIns = useStorage('sessionStorage');
const route = useRoute()
const router = useRouter()
// import calendar from '@/utils/lunar'; // import calendar from '@/utils/lunar';
// const currentTime = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss'); // const currentTime = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss');
// const lunarDay: any = calendar.solarToLunar( // const lunarDay: any = calendar.solarToLunar(
@ -111,11 +116,10 @@ const panelHeight = ref(0)
onMounted(() => { onMounted(() => {
// titleRef.value?.clientHeight; // // titleRef.value?.clientHeight; //
console.log(sidebar.value)
const offsetHeight = sidebar.value?.offsetHeight; // const offsetHeight = sidebar.value?.offsetHeight; //
sidebarHeight.value = offsetHeight === undefined ? 0 : offsetHeight - panelHeight.value sidebarHeight.value = offsetHeight === undefined ? 0 : offsetHeight - panelHeight.value
// menuShow.value=localStorage.getItem('menuShow')===undefined?true:JSON.parse(localStorage.getItem('menuShow')); // menuShow.value=localStorage.getItem('menuShow')===undefined?true:JSON.parse(localStorage.getItem('menuShow'));
console.log("sidebar:", sidebar.value?.offsetHeight) // console.log("sidebar:", sidebar.value?.offsetHeight)
}); });
window.addEventListener('resize', () => { window.addEventListener('resize', () => {
@ -125,6 +129,15 @@ window.addEventListener('resize', () => {
console.log("监听sidebar:", sidebar.value?.offsetHeight) console.log("监听sidebar:", sidebar.value?.offsetHeight)
}); });
onBeforeRouteLeave((to, from) => {
//
console.log("onBeforeRouteLeave--", to.path, from.path)
if (to.path != from.path) {
console.log('离开页面');
socket.close(false)
}
})
function tableMenuData(data: any) { function tableMenuData(data: any) {
// //
titleData.value = data[0].deptName titleData.value = data[0].deptName

Loading…
Cancel
Save