使用TypeScript客户端重新连接到Signalr

时间:2018-08-20 08:49:14

标签: javascript typescript websocket signalr

我使用signalR.HubConnection对象的onclose函数知道何时断开连接,然后尝试重新连接。

protected _hubConnection: signalR.HubConnection;

/**
 * Constructor
 * @param url
 * @param handlers
 */
constructor(url: string, onConnection: () => void, onDisconnection: (err: any) => void, handlers: Array<IHubConnectionHandler> = []) {

    this._hubConnection = new signalR.HubConnectionBuilder()
        .withUrl(url)
        .configureLogging(signalR.LogLevel.Information)
        .build();

    this._hubConnection.onclose(onDisconnection);
    this.initHandlers(handlers);
    this._hubConnection.start()
        .then(onConnection)
        .catch(err => console.log("ERROR ON START", err));
}

/**
 * When we get disconnected
 */
private onDisconnection(): void {
    console.log("DISCONNECTION");
    this.isOnline = false;
    this.isLoading = true;
    this.tryToReconnect();
}

/**
 * Try to reconnect to the hub
 */
private tryToReconnect(): void {
    if (!this.isOnline && !!this.isAuthorized) {

        // Time in second before trying to reconnect
        let interval: number = 5;

        this.chatHub.reconnect(this.onConnection);
        setTimeout(() => {
            if (!this.isOnline) {
                this.chatHub.hubConnection.stop();
                this.tryToReconnect();
            }
        }, interval * 1000);

    }
}

我尝试了很多事情,例如实例化集线器的新实例,手动停止连接以重试连接,但实际上没有任何效果。 我有时最终会遇到几个连接等等

0 个答案:

没有答案