前端:
引用signalr三方包
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import { defineStore } from "pinia";
|
||||
import * as signalR from '@microsoft/signalr';
|
||||
import { useMessage } from "@/components/messages/useAlert";
|
||||
import { useAuthStore } from "./auth";
|
||||
|
||||
const message = useMessage()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
export const useSignalRStore = defineStore('signalr', {
|
||||
state: () => ({
|
||||
connection: null,
|
||||
isConnected: false
|
||||
}),
|
||||
actions: {
|
||||
async initSignalR() {
|
||||
const url = import.meta.env.VITE_SIGNALR_BASE_URL || 'http://localhost:5202/chat';
|
||||
this.connection = new signalR.HubConnectionBuilder()
|
||||
.withUrl(url, {
|
||||
accessTokenFactory: () => {
|
||||
return authStore.token;
|
||||
}
|
||||
})
|
||||
.withAutomaticReconnect()
|
||||
.build();
|
||||
this.registerHandlers();
|
||||
try {
|
||||
await this.connection.start();
|
||||
this.isConnected = true;
|
||||
console.log('SignalR建立通信成功!')
|
||||
} catch (e) {
|
||||
message.error('与服务器建立通信失败,请检查网络连接...');
|
||||
}
|
||||
},
|
||||
registerHandlers() {
|
||||
this.connection.on('ReceiveMessage', (msg) => {
|
||||
console.log(msg)
|
||||
});
|
||||
|
||||
this.connection.onclose(() => { this.isConnected = false });
|
||||
this.connection.onreconnected(() => { this.isConnected = true });
|
||||
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user