当服务器关闭或重新启动时,SignalR 客户端不会调用重新连接事件

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

我创建了一个 hubConnection,并添加了 .WithAutomaticReconnect() 因此当连接丢失时它会自动重新连接。测试时我编写了 .Reconnecting 事件,当我停止服务器时,客户端 signalR 连接立即处于断开连接状态,并且在关闭事件中没有进入重新连接事件,并且不会重新连接。只有当我停止服务器时,如果服务器没有停止,并且连接以某种方式丢失,它会尝试重新连接并进入重新连接事件。那么,为什么当我停止服务器时没有触发 Reconnecting 事件? 我问这个是因为我想确保即使我在一些更新后重新启动服务器,客户端也会重新连接。仅使用 .WithAutomaticReconnect() 方法,如果服务器重新启动,客户端不会重新连接。

这是我的 signalR 连接构建代码:

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

我正在使用 signalR 3.0 并有一个 .net 核心控制台应用程序作为客户端。

发生这种情况是因为当您停止服务器时,它会发送服务器停止连接的事件,所以这不是由客户端或网络引起的连接丢失,因此重新连接没有意义,因为它是 "purposed" 连接结束.

所以,如果你在关闭服务器后还想重新连接,你需要自己实现。当服务器断开连接时,您会发现错误,您可以尝试重新连接。看这个例子:

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);
      });
  }