RT server and signalr
This commit is contained in:
46
front/src/services/signalr.ts
Normal file
46
front/src/services/signalr.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
HubConnection,
|
||||
HubConnectionBuilder,
|
||||
HubConnectionState,
|
||||
} from "@microsoft/signalr";
|
||||
|
||||
export class SignalRService {
|
||||
private connection: HubConnection;
|
||||
|
||||
constructor(
|
||||
hubUrl: string,
|
||||
) {
|
||||
this.connection = new HubConnectionBuilder()
|
||||
.withUrl(hubUrl)
|
||||
.withAutomaticReconnect()
|
||||
.build();
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.connection.state === HubConnectionState.Disconnected) {
|
||||
await this.connection.start();
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.connection.state !== HubConnectionState.Disconnected) {
|
||||
await this.connection.stop();
|
||||
}
|
||||
}
|
||||
|
||||
on<T>(event: string, handler: (data: T) => void) {
|
||||
this.connection.on(event, handler);
|
||||
}
|
||||
|
||||
off(event: string) {
|
||||
this.connection.off(event);
|
||||
}
|
||||
|
||||
async invoke<T = void>(method: string, ...args: any[]): Promise<T> {
|
||||
return await this.connection.invoke(method, ...args);
|
||||
}
|
||||
|
||||
get state() {
|
||||
return this.connection.state;
|
||||
}
|
||||
}
|
||||
21
front/src/services/testHubService.ts
Normal file
21
front/src/services/testHubService.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import {SignalRService} from "@/services/signalr.ts";
|
||||
|
||||
|
||||
const client = new SignalRService(
|
||||
`http://localhost:5039/testhub`,
|
||||
);
|
||||
|
||||
export const testHubService = {
|
||||
async connect() {
|
||||
await client.start();
|
||||
},
|
||||
/*
|
||||
async joinBoard(boardId: string) {
|
||||
await client.invoke("JoinBoard", boardId);
|
||||
},
|
||||
*/
|
||||
|
||||
onTest(callback: (text: string) => void) {
|
||||
client.on<string>("ReceiveText", callback);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user