Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make SignalR behave gracefully in case of disconnection

My application will often be used under fucked up corporate networks (proxy, firewalls, etc.) so I can not rely on sockets and long-polling is practically my only option. Here is my biggest problem with long-polling:

  1. Long-polling is disconnected at some point of time
  2. I automatically reconnect (accoring to documentation)
  3. User clicks something that causes hub method call but connection is not established yet - error happens.

Is there any way to synchronize hub method call and reconnection like:

  1. I call hub method
  2. SignalR sees connection is not ready yet
  3. It waits till connection is ready and calls a hub method afterall

For now I don't see such an oportunity and it seems like my only option is to switch to ajax calls which is sad.

like image 600
SiberianGuy Avatar asked Oct 28 '25 06:10

SiberianGuy


1 Answers

How I deal with it:

  • have a isConnected boolean on my client so that whenever I connect, I set it to true, and whenever I disconnect I set it back to false:

    $.connection.hub.start().fail((err) => { alert(err); }).done(() => this.isConnected = true); $.connection.hub.disconnected(() => { this.isConnected = false; }); $.connection.hub.reconnected(() => { this.isConnected = true; });

  • now, right before I make the call to a hub method, I check if isConnected is true. If not, I attempt start the hub connection:

    $("#serverButton").click(function(){ if(this.isConnected==false) $.connection.hub.start(); $.connection.hub.server.serverMethod();
    })

This is how I handle such situations right now. Hope this helps. Best of luck!

UPDATE: There actually exists a property on $.connection.hub called state that you can access at every point during the connection.

So you can skip the step of having your own variable (though I still use it just to be sure) by checking $.connection.hub.state.

$.connection.connectionState Object {connecting: 0, connected: 1, reconnecting: 2, disconnected: 4}

The output from $.connection.hub.state is an integer from the ones above, but you can do something like this: $.connection.hub.state == $.signalR.connectionState.connected and you can have booleans.

Easier, but you still have to check this every time you make a call to a hub method.

like image 72
radu-matei Avatar answered Oct 30 '25 15:10

radu-matei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!