2024-06-22 10:54:02 +08:00
|
|
|
|
// 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()
|
2024-06-29 19:01:09 +08:00
|
|
|
|
.withUrl(`${useRuntimeConfig().public.baseUrl}/SessionHub`,{
|
|
|
|
|
accessTokenFactory:()=> `${useCookie('token').value}`
|
|
|
|
|
})
|
2024-06-22 10:54:02 +08:00
|
|
|
|
.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未连接,无法发送消息');
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|