LoongPanel-Asp/web/strores/HubStore.ts

85 lines
2.9 KiB
TypeScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// src/stores/signalr.ts
import {defineStore} from 'pinia';
import {HubConnection, HubConnectionBuilder} from '@microsoft/signalr';
import {useToast} from 'vue-toastification'
//获取useToast对象
const toast = useToast()
export const useSessionSignalRStore = defineStore('sessionSignalR', {
state: () => ({
connection: null as HubConnection | null,
isConnected: false,
}),
actions: {
// 初始化SignalR连接
initConnection() {
// 构建连接
this.connection = new HubConnectionBuilder()
.withUrl(`${useRuntimeConfig().public.baseUrl}/SessionHub`)
.withAutomaticReconnect()
.build();
// 设置自动重连策略
this.connection.onreconnecting(error => {
console.log('SignalR正在尝试重新连接:', error);
toast.info('正在尝试重新链接会话服务器', {
timeout: 3000,
})
});
this.connection.onreconnected(connectionId => {
console.log('SignalR已重新连接新的连接ID:', connectionId);
this.isConnected = true;
toast.success('会话服务器重新连接成功', {
timeout: 3000,
})
});
this.connection.onclose(error => {
console.log('SignalR连接已关闭:');
this.isConnected = false;
});
// 启动连接
this.start().then(
() => {
toast.success('会话服务器链接成功', {
timeout: 3000,
})
}
)
},
// 启动SignalR连接
async start() {
try {
await this.connection?.start();
this.isConnected = true;
console.log('SignalR已连接');
} catch (error) {
console.log('SignalR连接失败:', error);
setTimeout(() => this.start(), 5000); // 5秒后尝试重新连接
}
},
// 停止SignalR连接
async stop() {
try {
await this.connection?.stop();
this.isConnected = false;
console.log('SignalR已断开连接');
} catch (error) {
console.log('SignalR断开连接失败:', error);
}
},
// 添加方法来发送消息到服务器
sendMessage(methodName: string, ...args: any[]) {
if (this.isConnected && this.connection) {
this.connection.invoke(methodName, ...args).catch(error => {
console.error('SignalR发送消息失败:', error);
});
} else {
console.warn('SignalR未连接无法发送消息');
}
},
},
});