SignalR fails to send message to a group when running through LoadBalancer - signalr

In order to send SignalR message to a specific user I create a Group for each user upon connection
public override Task OnConnected()
{
log.DebugFormat("Connected. Connection Id = {0} UserId = '{1}'", Context.ConnectionId, UserHelper.UserId);
Groups.Add(Context.ConnectionId, UserHelper.UserId);
return base.OnConnected();
}
Now when a message comes in I send it a group in the following way:
var hubContext = GlobalHost.ConnectionManager.GetHubContext<AlertsHub>();
foreach (var recipient in recipients)
{
hubContext.Clients.Group(recipient).broadcastAlertMessage("Group", msg);
}
That works fine when deployed to a server, but for some reason not working when i access the server through our company load balancer (Citrix Netscaler SDX 11500) but eventually hitting the same sole box.
There is no issue sending messages to all clients
hubContext.Clients.All.broadcastAlertMessage("All", msg);
Also i can keep the connection IDs internally and send messages to a specific client works
hubContext.Clients.Client(AlertsHub.UserToConnectionIdDict["admin"]).broadcastAlertMessage("trageted client", msg);
Why "Group" message doesn't work?

By default, a SignalR server is only aware of and will only send messages to clients connected directly to itself. This is because each SignalR server manages its own messages using its own message bus. Without special configuration, SignalR has no way to know there are other clients connected to a different SignalR server at the same global address.
Fortunately SignalR has scaleout providers that allow you to configure all your SignalR servers in such a way that they can communicate with each other by sharing single message bus.
This "Introduction to Scaleout in SignalR" should provide you with the info you need to get SignalR working properly behind a load balancer: http://www.asp.net/signalr/overview/signalr-20/performance-and-scaling/scaleout-in-signalr

Related

Signalr with redis backplane, sending message to user

I am researching to use signalr to send messages from an api to a specific user (keyword). Locally, I have everything working as designed (even using redis backplane).
When I move up to an actual environment with multiple servers (azure app service), it seems like messages to specific users don't flow through the backplane. If I send a message to Clients.All it works. But, if I send a message to Clients.User(username), the message is never received. This works locally because it's a single server, but doesn't seem to work in multiple servers.
await this.impersonationContext.Clients.User(mainUserName).SendAsync("msguser", new object[] { mainUserName });
await this.impersonationContext.Clients.All.SendAsync("msg", new object[] { "wtf" });
If I call the above code, only the msg event is fired, but the msguser is never recieved.
Could I be missing something on the setup? That's my assumption, I cannot be the only one doing this.
Below is my setup in the startup.cs. This is using .net core 5 with the latest nugets, etc
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
})
.AddStackExchangeRedis(this.Configuration["Redis:Cache"], options => {
options.Configuration.ChannelPrefix = "ImpersonationService";
});
services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
Any help would be appreciated.
Update #1
Looks like the user info is being pushed through the backplane (username hidden). So maybe its the connection from javascript client?
Update #2
Getting closer...looks like the subscription isn't setup for the specific user like I see locally. Could this be websockets?
Update #3
Found it....sorta.
I was missing the authorize attribute on the hub, which was allowing the websocket to connect, even though websockets isn't authenticating for some reason (different issue). Once I added the authorize, it will drop down to long polling with the user info and works as designed

SignalR Validate WinForm Client Integrity

From the SignalR hub, i want to enforce the connecting client is the WinForm program I distributed. Is there a way to "challenge" the client from the hub, by asking for a secret, or code signing certificate, or checksum of the exe, or anything?
SignalR connection does not intended for such purposes - it just connects to a service hub. You can always challenge a user on WinForm side before connection run
if (secretValue == inputSecret) {
await hubConnection.Start();
} else {
// notify user that secret is incorrect
}

SignalR and switching servers and connection lost

SignalR is running on a certain Server with an open connnection. If we need to bring up another server, then take the original down does SignalR automatically reconnect with the NEW server and start functioning like it was on the first?
We had a similar problem and what we discovered was that SignalR does not automatically reconnect with the new server. Our solution to was to not use the generated proxy. We used an intermediary endpoint whose job it is to provide the current url to use. To connect to SignalR our flow calls the endpoint gets the result using that result we connect to that server for SignalR then when the SignalR connection closes or is lost we repeat the process again as if for the first time.
async function reconnect(connection){
const signalRUrl = await request('<<our intermediary url>>');
connection.hub.url = signalRUrl;
connection.start();
}
var connection = $.hubConnection();
var hubProxy = connection.createHubProxy('yourHub');
hubProxy.on('message',function(){});
await reconnect(connection);
connection.onClose(function () {
reconnect(connection);
});

How to establish one-to-one connection between the clients using signalr?

I was developing a webapplication using signalr but i am having problem sending text to specific user in the connection.
Please use the following :
Clients.Client(ConnectionId).OnMessage(MessageText)
Get current signalr hub
private IHubContext _hub =GlobalHost.ConnectionManager.GetHubContext<SignalRHubName>()
Send Message to client by invoking the method in client side
_hub.Clients.Client(signalrconnectionId).signalRMethodInClient(message);
Since you want to send a message to a specific client you can keep a mapping between singalrid and your client id and use that mapping to get the signalrconnectionId for a client when needed.

Isolating specific browser instance with SignalR

We are building an app which will send messages to the browser using SignalR. The user may have multiple browser instances open and we would like each message to be sent to the appropriate browser. Our understanding is that the ClientId ConnectionId would allow us to do this. The issue we're running into is accessing the ClientId ConnectionId, or SessionId, at the appropriate times in the codebase. Here's our scenario:
A MVC Action executes and, as part of that processing, a call to a Biztalk endpoint is made. The Biztalk execution is out of process (from the point of view of the MVC Action) and doesn't return when completed. This is by design. To notify the MVC application that it has completed, Biztalk sends a message to the MVC application's SignalR hub by calling the /myapp/signalr endpoint. The message is received by SignalR and then should be routed to the appropriate browser instance.
Since the message to SignalR is being sent by Biztalk, and not the MVC application, the ClientId of the connection to SignalR is not the one that identifies the browser instance that should receive the message. So what we are attempting to implement is somethign similar to the Return Address pattern by including the ClientId ConnectionId of the browser instance that initiates the Biztalk call in the message to Biztalk. When Biztalk sends its message to SignalR one of the contents is that original ClientId ConnectionId value. When SignalR processes the message from Biztalk it then can use the ClientId ConnectionId included in the message to route that message to the appropriate browser instance. (Yes we know that this won't work if the browser has been closed and re-opened and we're fine with that.)
The problem we face is that when initially sending the message to Biztalk from our MVC Action we cannot access the ClientId ConnectionId as it's only available in the Hub's Context. This is understandable since the MVC Action doesn't know which Hub context to look for.
What we have tried in it's place is to pass the SessionId through the Biztalk message and return it to SignalR. This solves the problem of including the browser instance identifier in the Biztalk message and returning it to SignalR. What it introduces is the fact that when a client connects to the Hub we cannot access the Session (and thus the SessionId) in the Hub's OnConnect method.
David Fowler posted a gist that reportedly shows how to make readonly SessionState accessible in a Hub but it doesn't work. (https://gist.github.com/davidfowl/4692934) As soon as we add this code into our application messages sent to SignalR cause a HTTP 500 error which is caused by SignalR throwing the following exception.
[ArgumentNullException: Value cannot be null.Parameter name: s]
System.IO.StringReader..ctor(String s) +10688601
Microsoft.AspNet.SignalR.Json.JsonNetSerializer.Parse(String json, Type targetType) +77
Microsoft.AspNet.SignalR.Json.JsonSerializerExtensions.Parse(IJsonSerializer serializer, String json) +184
Microsoft.AspNet.SignalR.Hubs.HubRequestParser.Parse(String data) +101
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReceived(IRequest request, String connectionId, String data) +143
Microsoft.AspNet.SignalR.<>c__DisplayClassc.<ProcessRequest>b__7() +96
Microsoft.AspNet.SignalR.<>c__DisplayClass3c.<FromMethod>b__3b() +41
Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(Func`1 func) +67
No matter the mode that we set SessionStateBehavior (as shown by David Fowler's gist) we either get this exception when sending a message to the Hub or SessionState is null when we are in the Hub's OnConnect.
So, after all that pre-amble, what we are asking is how do people update the appropriate client when working with this type of disconnected messaging in SignalR?
If you're looking to send data to clients outside of a normal request to a hub then I'd recommend having a static Concurrent Dictionary on your hub that manages your users and maps them to corresponding connection Id's.
With this approach you can send to any user at any point based on their mapped Connection Id. Therefore when sending your data to Biztalk all you need to do is send your user id (created by you) and then when the data flows back to SignalR you can lookup the ConnectionId (if one exists) for that given user id.
Lastly, you can manage your user mappings by adding users to your concurrent dictionary in OnConnected, adding only if they are not there in OnReconnected, and removing in OnDisconnected.

Resources