Angular SignalR 可以打开多个 WebSocket。在 Angular 中,可以使用 SignalR 的 HubConnectionBuilder
和 HubConnection
类来启动和管理与服务器的 WebSocket 连接。以下是一个示例:
import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';
@Injectable({
providedIn: 'root'
})
export class MySignalRService {
private hubConnection: signalR.HubConnection;
constructor() { }
public startConnection() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('/my-hub')
.build();
this.hubConnection.start()
.then(() => console.log('SignalR connection started'))
.catch(err => console.error('Error while starting SignalR connection: ' + err));
}
public stopConnection() {
this.hubConnection.stop()
.then(() => console.log('SignalR connection stopped'))
.catch(err => console.error('Error while stopping SignalR connection: ' + err));
}
public addListener(eventName: string, callback: (...args: any[]) => void) {
this.hubConnection.on(eventName, callback);
}
public removeListener(eventName: string, callback: (...args: any[]) => void) {
this.hubConnection.off(eventName, callback);
}
public send(eventName: string, ...args: any[]) {
this.hubConnection.invoke(eventName, ...args)
.catch(err => console.error('Error while sending SignalR message: ' + err));
}
}