Search code examples
signalrsignalr-hub

Can I get results from multiple SignalR clients from Hub


I want to implement a SignalR logging, where the server will regularly ping all it's clients for any accumulated logs.

Microsoft isn't exactly clear on this: docs

What I don't understand is if there is a way to get results from all clients at once. Something like:

var logsFromAllClients = _hubContext.Clients.All.SendLogs();

However this obviously doesn't work, because Clients.All is simply my strongly-typed client T. Which means that it can only get results from one client. I'm curious as to what will happen if invoked with multiple active clients?

Another idea is to iterate over all active connections and request each client's logs individually. As far as I can tell this is also not supported outside of the box. Would I be able to store active connection ids in a collection and iterate over them to achieve this.

Is there anything else I'm missing?


Solution

  • There's no mechanism on the SignalR server to send a message to more than one client simultaneously and get a return value from each. ISingleClientProxy is for invoking methods, with a return value, on a single client. This can be obtained from IHubClients.Client(string connectionId) for example, but only for a single client connection id at a time and there's no built-in way to iterate through all open connections.

    I suppose you could cache connection IDs yourself as they subscribe and iterate through them by getting their ISingleClientProxy, but this would not be a great practice. You have no control over when or whether a client will respond while you wait to send to the next client in the loop and the client list could easily change while the loop iterates.

    A better practice would be to just blast them all a single message instructing them to send you their logs, via _hubContext.Clients.All.SendAsync("SendLogs"). The client-side SendLogs method invoked on each client machine will then turn around and call an additional server-side method in order to actually provide their logs. You'll need to handle these passively as they come in and realize they will arrive in an unpredictable order. I would suggest a standard API POST for this rather than a SignalR invocation.

    Also be careful as you could get a LOT of data really quickly depending on how much this is expected to scale.