SignalR 可以在客户端断开连接时对消息进行排队,并在客户端重新连接时将消息重新发送给客户端吗?

Dhr*_*shi 7 signalr signalr-hub signalr.client signalr-backplane asp.net-core-signalr

目前,我们使用 SignalR 在 UI 客户端上从后端接收实时消息。UI 客户端在在线并连接到 SignalR 时接收消息,并在断开连接时错过消息(例如:用户关闭页面并且 SignalR 断开客户端连接)。但是,现在我们需要向用户显示所有消息,包括 UI 客户端离线时 SignalR 发送的消息。SignalR 可以支持这种场景吗?该要求类似于 UI 客户端消息的持久队列,但我们使用 SignalR 向所有客户端广播消息。

Kir*_*512 3

SignalR does not support this scenario, you need to do it on your own. You need to store the the messages and implement a hub method that will send the pending data to the connected client. So what you need to do is:

  • Save the data on some volatile storage with a readby option, so you can see data that was already send to the client and delete it.
  • Hub method that will sent data to the client and the client responds that received the data.
  • Hub method that will send all data that was not sent by hub when client was disconnected.

Code example, on the client side, connect and get previous data:

/**
* Connect signalR and get previous data
*/
private async connectSignalR() {
  await this.hubMessageConnection.start()
    .then(() => {
      // Register application
      this.GetDataForThisClientAsync();
    }).catch(() => {
      this.onError.emit(WidgetStateEnum.connectError);
    });
}
Run Code Online (Sandbox Code Playgroud)

And hub method to get data:

public async Task<OperationResult> GetNotificationsAsync(Groups groups)
{
    IList<MyData> data = await this.DataManager.GetDataForThisClientAsync(groups).ConfigureAwait(false);

    if (data.Count != 0)
    {
        // Send the notifications

        foreach (MyData data in datas)
        {
            await this.BroadcastDataToCallerAsync(data).ConfigureAwait(false);
        }
    }

    return OperationResult.Success();
}