🚀 0.4.1

优化WebSocket连接逻辑
This commit is contained in:
hi2hi 2024-12-06 10:09:33 +00:00
parent 5666efa542
commit ca50ac15c7
4 changed files with 49 additions and 19 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "nazhua", "name": "nazhua",
"version": "0.4.0", "version": "0.4.1",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@ -26,6 +26,9 @@ const currentTime = ref(0);
provide('currentTime', currentTime); provide('currentTime', currentTime);
/**
* 刷新当前时间
*/
function refreshTime() { function refreshTime() {
currentTime.value = Date.now(); currentTime.value = Date.now();
setTimeout(() => { setTimeout(() => {
@ -40,6 +43,9 @@ function handleSystem() {
} }
} }
/**
* websocket断连的自动重连
*/
let stopReconnect = false; let stopReconnect = false;
async function wsReconnect() { async function wsReconnect() {
if (stopReconnect) { if (stopReconnect) {
@ -55,7 +61,15 @@ async function wsReconnect() {
onMounted(async () => { onMounted(async () => {
handleSystem(); handleSystem();
refreshTime(); refreshTime();
/**
* 初始化服务器信息
*/
await store.dispatch('initServerInfo'); await store.dispatch('initServerInfo');
/**
* 初始化WS重连维护
*/
msg.on('close', () => { msg.on('close', () => {
console.log('ws closed'); console.log('ws closed');
wsReconnect(); wsReconnect();
@ -68,14 +82,17 @@ onMounted(async () => {
console.log('ws connected'); console.log('ws connected');
store.dispatch('watchWsMsg'); store.dispatch('watchWsMsg');
}); });
activeWebsocketService();
//
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
if (wsService.connected !== 1) { // ws
// -1
if ([-1].includes(wsService.connected)) {
restart(); restart();
} }
}); });
/**
* 激活websocket服务
*/
activeWebsocketService();
}); });
window.addEventListener('unhandledrejection', (event) => { window.addEventListener('unhandledrejection', (event) => {

View File

@ -3,8 +3,12 @@ import MessageSubscribe from '@/utils/subscribe';
import { import {
handelV1toV0, handelV1toV0,
} from '@/utils/load-nezha-v1-config'; } from '@/utils/load-nezha-v1-config';
import WSService from './service'; import WSService from './service';
/**
* 获取不同版本的WebSocket路径
*/
function getWsApiPath() { function getWsApiPath() {
if (config.nazhua.nezhaVersion === 'v1') { if (config.nazhua.nezhaVersion === 'v1') {
return config.nazhua.v1WsPath; return config.nazhua.v1WsPath;
@ -25,7 +29,8 @@ const wsService = new WSService({
msg.emit('error', error); msg.emit('error', error);
}, },
onMessage: (data) => { onMessage: (data) => {
if (data?.now) { // 消息体包含.now和.servers 粗暴的判定为服务器列表项信息
if (data?.now && data?.servers) {
if (config.nazhua.nezhaVersion === 'v1') { if (config.nazhua.nezhaVersion === 'v1') {
msg.emit('servers', { msg.emit('servers', {
now: data.now, now: data.now,
@ -57,17 +62,20 @@ export {
}; };
export default (actived) => { export default (actived) => {
// console.log('wsService active'); if (wsService.connected === 2) {
if (wsService.connected === 1) {
if (actived) { if (actived) {
actived(); actived();
} }
return; return;
} }
wsService.active();
msg.once('connect', () => { msg.once('connect', () => {
if (actived) { if (actived) {
actived(); actived();
} }
}); });
// 如果已经连接中,则不再连接
if (wsService.connected === 1) {
return;
}
wsService.active();
}; };

View File

@ -1,11 +1,5 @@
class WSService { class WSService {
constructor(options) { constructor(options) {
// 确保单例模式
if (WSService.instance) {
return WSService.instance;
}
WSService.instance = this;
const { const {
wsUrl, wsUrl,
onConnect, onConnect,
@ -25,6 +19,15 @@ class WSService {
message: onMessage || (() => {}), message: onMessage || (() => {}),
messageError: onMessageError || (() => {}), messageError: onMessageError || (() => {}),
}; };
// 单例模式 遇到重复的ws服务不再允许建立新的ws消息处理如果遇到问题等待用户自行刷新页面破罐子破摔解决方法
if (WSService.instance) {
// 抛出错误,防止重复创建 WebSocket 连接
this.$on.error(new Error('WebSocket connection already exists'));
return;
}
WSService.instance = this;
// 0: 未连接1: 连接中2: 已连接,-1: 已关闭 // 0: 未连接1: 连接中2: 已连接,-1: 已关闭
this.connected = 0; this.connected = 0;
this.ws = undefined; this.ws = undefined;
@ -50,14 +53,15 @@ class WSService {
} }
active() { active() {
if (this.connected !== 0) { // 如果已经连接中或已连接,则不再连接
if (this.connected > 0) {
console.warn('WebSocket connection already exists or is connecting'); console.warn('WebSocket connection already exists or is connecting');
return; return;
} }
// 标记为正在连接中 // 标记为正在连接中
this.connected = 1; this.connected = 1;
// 创建 WebSocket 连接 // 创建 WebSocket 连接
this.ws = new WebSocket(this.$wsUrl); this.ws = new WebSocket(this.$wsUrl);
this.ws.addEventListener('open', (event) => { this.ws.addEventListener('open', (event) => {
@ -77,7 +81,8 @@ class WSService {
}); });
this.ws.addEventListener('message', this.evt); this.ws.addEventListener('message', this.evt);
this.ws.addEventListener('error', (event) => { this.ws.addEventListener('error', (event) => {
console.error('ai-live-websocket error', event); console.log('socket error', event);
WSService.instance = null; // 清除实例引用
this.$on.error(event); this.$on.error(event);
}); });
} }