zhuangpeimespda/utils/signalrUtil.js
2025-05-05 12:22:51 +08:00

49 lines
1.3 KiB
JavaScript

import * as signalR from '@microsoft/signalr';
import { getToken } from '@/utils/auth'
class SignalRUtil {
constructor(url) {
console.log('SignalR 连接:',url);
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(url)
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Warning)
.build();
this.hubConnection.onclose(() => {
console.log('SignalR 连接已关闭');
});
}
async startConnection() {
try {
await this.hubConnection.start();
console.log('SignalR 连接已建立');
} catch (error) {
console.error('SignalR 连接失败:', error);
}
}
on(methodName, callback) {
this.hubConnection.on(methodName, callback);
}
async invoke(methodName, ...args) {
try {
return await this.hubConnection.invoke(methodName, ...args);
} catch (error) {
console.error('调用 SignalR 方法失败:', error);
}
}
async stopConnection() {
try {
await this.hubConnection.stop();
console.log('SignalR 连接已停止');
} catch (error) {
console.error('停止 SignalR 连接失败:', error);
}
}
}
export default SignalRUtil;