SignalR client disconnected on Azure slots swap - signalr

I have web app on Azure with 2 slots.
Whenever the slot swap happens, all SignalR clients are disconnected and not even notified about the connection loss.
SignalR events such a Close, Error, Reconnected are never fired on the client.
How to prevent this or at least know when disconnect happens? (of course I need to avoid polling)

How to prevent this or at least know when disconnect happens?
We could enable SignalR tracing to view diagnositc infomration about events in your SignalR application. How to enable and configure tracing for SignalR servers and clients, we could refer to this document.
Detecting the reason for a disconnection
SignalR 2.1 adds an overload to the server OnDisconnect event that indicates if the client deliberately disconnected rather than timing out. The StopCalled parameter is true if the client explicitly closed the connection. In JavaScript, if a server error led the client to disconnect, the error information will be passed to the client as $.connection.hub.lastError.
C# server code: stopCalled parameter
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
if (stopCalled)
{
Console.WriteLine(String.Format("Client {0} explicitly closed the connection.", Context.ConnectionId));
}
else
{
Console.WriteLine(String.Format("Client {0} timed out .", Context.ConnectionId));
}
return base.OnDisconnected(stopCalled);
}
JavaScript client code: accessing lastError in the disconnect event.
$.connection.hub.disconnected(function () {
if ($.connection.hub.lastError)
{ alert("Disconnected. Reason: " + $.connection.hub.lastError.message); }
});
More details we could refer to Detecting the reason for a disconnection.
How to prevent this?
We could continuously reconnect it.
In some applications you might want to automatically re-establish a connection after it has been lost and the attempt to reconnect has timed out. To do that, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients). You might want to wait a period of time before calling Start in order to avoid doing this too frequently when the server or the physical connection are unavailable. The following code sample is for a JavaScript client using the generated proxy.
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
});
More details we could refer to How to continuously reconnect

Related

Spring WebFlux Broken Stream Error Handling

I'm struggling to find any good examples on how to implement error handling with Spring WebFlux.
The use case I want to handle is notifying HTTP clients that a stream has terminated unexpectedly. What I have found it that with the out of the box behaviour, when a stream is terminated, for example by raising a RuntimeException after x items have been processed, is handled too gracefully! The client is flushed all items up until the exception is raised, and then the connection is closed. As far as the client is concerned the request was successful. The following code shows how this has been setup:
public Mono<ServerResponse> getItems(ServerRequest request) {
Counter counter = new Counter(0);
return ServerResponse
.ok()
.contentType(MediaType.APPLICATION_STREAM_JSON)
.body(operations.find(query, Document.class, "myCollection")
.map(it -> {
counter.increment();
if(counter.getCount() > 500) {
throw new RuntimeException("an error has occurred");
}
return it;
}), Document.class);
}
What is the recommended way to handle the error and notify the HTTP client that the stream terminated unexpectedly?
It really depends on how you'd like to communicate that failure to the client. Should the client display some specific error message? Should the client reconnect automatically?
If this is a "business error" that doesn't prevent you from writing to the stream, you could communicate that failure using a specific event type (look at the Server Sent Events spec).
Spring WebFlux supports ServerSentEvent<T>, which allows you to control various fields such as event, id, comment and data (the actual data). Using an Flux::onErrorMap operator, you could write a specific ServerSentEvent that has an "error" event type (look at the ServerSentEvent.builder() for more).
But this is not transparent to the client, as you'd have to subscribe to specific events and change your JavaScript code otherwise you may display error messages as regular messages.

Signalr server messages to client cancelled (specific clients only)

I use signalR to display currently connected users. Some clients are failing to see the connected clients because the server to client connection is being cancelled by the client as shown below:
Below is my js code:
var progressNotifier = $.connection.activeConnectionsHub;
$.connection.hub.start().done(function () {
progressNotifier.server.showActiveConnections();
// code here
});
// client-side sendMessage function that will be called from the server-side
progressNotifier.client.addConnections = function (param) {
// code here never gets called
}
This only happens on some client browsers.
I tried disabling antivirus, firewall, malware etc. But it is still not working.
Does anyone have an idea what is causing this issue?

SignalR doesn't use 'on' subscription after connection to server is started

I have SignalR working with an Angular client, but I can't get proxy.on() to work if the connection is established before I subscribe to events.
My server method invokes the client method pushToClient on both hubs.
var connection1 = $.hubConnection(); //Works fine since I started connection AFTER subscribing
var proxy1 = connection1.createHubProxy('clientPushHub');
proxy1.on('sendToClient', function (message) {
console.log('This will work: ' + message);
});
connection.start();
var connection2 = $.hubConnection(); // Doesn't work when I start the connection BEFORE subscribing
var proxy2 = connection2.createHubProxy('clientPushHub');
connection2.start();
proxy2.on('sendToClient', function (message) {
console.log('This will not work: ' + message);
});
If I change things so that proxy2 subscribes to pushToClient before starting connection2, it works fine. Also tried doing the 'on' subscription in the start().done() callback but that did not work.
I've downloaded and verified this example works as I expected when subscribing after connecting, and this ASP.NET article/section specifically mentions you can do things in this order if you don't use a generated proxy, which I haven't.
What worked for the asker in this SO question does not work for me.
Any ideas where I might have gone wrong?
Based on this post, it sounds like you have to have at least one event listener prior to calling start. From there you can add more event handlers using the 'on' functionality.
EDIT:
Try this.
proxy2.on('foo',function(){});
connection2.start();
proxy2.on('sendToClient', function (message) {
console.log('This will not work: ' + message);
});
Also this is from the article you linked you for post:
Note: Normally you register event handlers before calling the start method to establish the connection. If you want to register some event handlers after establishing the connection, you can do that, but you must register at least one of your event handler(s) before calling the startmethod. One reason for this is that there can be many Hubs in an application, but you wouldn't want to trigger the OnConnected event on every Hub if you are only going to use to one of them. When the connection is established, the presence of a client method on a Hub's proxy is what tells SignalR to trigger the OnConnected event. If you don't register any event handlers before calling the start method, you will be able to invoke methods on the Hub, but the Hub'sOnConnected method won't be called and no client methods will be invoked from the server.

SignalR not firing "disconnected" event

I'm using SignalR to push updates out to connected web clients. I listen to the disconnected event in order to know when I should start my reconnection logic
$.connection.hub.disconnected(function() {
// Initiate my own reconnection logic
});
The SignalR hub is hosted in in IIS (along with my site)
[assembly: OwinStartup(typeof(Startup))]
namespace MyNamespace.SignalR
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Upon connection, the client calls a server method to join a group
public class MyHub : Hub
{
public void JoinGroup(string groupName)
{
Groups.Add(Context.ConnectionId, groupName);
}
}
And then I push messages to this group:
context.Clients.Group(groupName).sendMessage();
If I manually recycle the application pool in IIS, SignalR starts trying to reconnect and I eventually receive a disconnected event on the client side if it fails (after the timeout).
However, my problem is that if I manually restart the website in IIS, I do not receive any disconnected event at all, and I can't see in the logs that SignalR has detected any connection problem at all. How can I detect that I have been disconnected?
I know I should probably persist the group connections somehow, since that is saved in memory I guess. But that shouldn't affect the initial problem that the client receives no notification of the disconnection? Shouldn't the client side signalr code throw some kind of exception/event?
disconnected fires first when the built in logic for reconnection have timed out. You also need to listen to the recconect event, something like i did here
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/ReconnectOnClosed/SignalR.EventAggregatorProxy.Client.JS/jquery.signalR.eventAggregator.js#L157
So I finally found out what the problem is and how to solve it. Some background though:
At the moment we manually release new versions of our application by going to "Basic settings..." under the website in IIS and changing the "Physical Path" from C:\websites\version1 to C:\websites\version2. Apparently this gives the same behavior as doing a restart of the website in IIS (not a hard reset, not stopping the website, not recycling the app pool) and according to this: "does NOT shut the site down, it merely removes the Http.sys binding for that port". And no matter how long we wait, the connected clients never receive any kind of indication that they should reconnect.
So the solution is to recycle the application pool after each release. The "lost" clients will receive disconnected events and reconnect to the new version of the site.

Unexpected Signalr connection abort in Firefox

I am using SignalR (with cross-domain request), version 2.3.0 for webchat integrated to ASP.NET site. Everything is working fine. But I found strange behaviour of SignalR connection. When I clicked to the reference from tab of the chat for file downloading SignalR connection was aborted and onDisconnected method was triggered in my Hub class. FireBug show me next POST-request:
http://*:81/signalr/abort?transport=longPolling&clientProtocol=1.4&token=eUpLNitKcmR1d2JhTTRvcHNVZmEwcG1EKzYvMElZbmg4aE5yam9xM3k0dz0_IjAsNGJmOWNhODUtNDU2NS00NWExLWFjMTgtNzgyN2FhZDA2Njg1LGxvY2FsaG9zdCI1&State=1&connectionToken=hDXe9xIZtmrapjl1LRwtK9B%2BfYMoeuHka8ctBLaPa0YnjiN9iiFa%2BvFMBHIGpGH0h8qPEDgGZSRGwjMw3Wm1DJi6cUPtZjLca6%2FR2576SGksLAj3lnPN1JWIlxMsn8%2Bf&connectionData=%5B%7B%22name%22%3A%22c%22%7D%2C%7B%22name%22%3A%22voip%22%7D%5D, where * is my domain.
It is reproduced in Mozilla Firefox (version 30.0) for LongPolling or Websocket transports. How I can fix this problem? Or is it bug of SignalR or Firefox?
This bug has been recently filed against SignalR on GitHub. The basic idea is that downloading a file causes Firefox to trigger the window.onbeforeunload event which in turn causes SignalR to close any ongoing connections.
For now, the workaround is to attach a handler to the client's disconnected event that will call $.connection.start again after a short window.setTimeout.
You could also unbind SignalR's onbeforeunload handler: $(window).unbind("beforeunload"). The downside of doing this is that Firefox might not gracefully disconnect when the user leaves the page running SignalR. Without a graceful disconnect, SignalR will wait over 30 seconds before it times out the client and calls the OnDisconnected handler on the Hub or PersistentConnection.
I have managed to use the workaraound explained by halter73 and I have solved the issue described by dudeNumber4 resetting the connectionid inside the disconnect event so that the server kept calling back the right users based on their connectionid without the need to address them by their user or group names.
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start().done(function () {
$("#mySignalRConnectionIdHidden").val($.connection.hub.id);
});
}, 3000);
});

Resources