Pupuc
Pupuc

Reputation: 23

SignalR client does not call the reconnecting event when the Server shuts down, or restarts

I created a hubConnection, and added the .WithAutomaticReconnect() so when the connection is lost it will automaticaly reconnect. When testing i wrote the .Reconnecting event, and when i stop the server, the client signalR connection is going immediately in the Disconnected state, and in the Closed event without going in the Reconnecting event, and does not reconnect. This is only when i stop the server, if the server is not stoped, and the connection is somehow lost, it does try to recconect and it goes in the Reconnecting event. So, why the Reconnecting event is not fired when i stop the server? I am asking this because i want to make sure the client will reconnect even if I restart the server after some updates. With only the .WithAutomaticReconnect() method, the client does not reconnect if the server was restarted.

This is my code for the signalR connection build:

_hubConnection = new HubConnectionBuilder().WithUrl(Url, options =>
                 {
                     options.AccessTokenProvider = () => Task.FromResult(token);
                 })
                .WithAutomaticReconnect()
                .Build();

I am working with signalR 3.0 and have a .net core console app as client.

Upvotes: 2

Views: 3712

Answers (1)

Kiril1512
Kiril1512

Reputation: 3611

This happens because when you stop the server, it sends the event that the server stopped the connection. So, this is not a connection loss caused by client or the network, therefore there is no sense to reconnect, because it was a "purposeful" connection end.

So, if you still want to reconnect when you turn of the server, you need to implement the it by yourself. When the server disconnects you will catch the error and you can try to connect again. See this example:

private async connectSignalR() {
    await this.hubMessageConnection.start()
        .then(() => {
        this.doSomething();
    }).catch(() => {
        this.onError.emit(WidgetStateEnum.connectionClose);
    });
}
  
private configureSignalR(signalRUrl: string, token: string) {
    this.hubMessageConnection = new signalR.HubConnectionBuilder()
    .configureLogging(signalR.LogLevel.Error).withUrl(signalRUrl + "/yourHubEndpoint",
    {
        accessTokenFactory: () => token
    })
    .withAutomaticReconnect()
    .build();

    this.hubMessageConnection.onclose(() => {
        this.connectionClose();
    });
}
    
private connectionClose() {
    this.onError.emit(WidgetStateEnum.connectionClose);
    this.doSomethingWhenConnectionIsClose();
}.catch(() => {
        this.onError.emit(WidgetStateEnum.connectionClosed);
      });
  }

Upvotes: 2

Related Questions