38

I've seen how you can trap a disconnection event on the client side with SignalR by binding to the .disconnect event.

Now that I've done this, I want to put the client into a "waiting to reconnect cycle" where it continually tries to connect until it succeeds or the user cancels out. Does the hub expose a connection state property? I'm thinking something like (pseudo code)

var isConnected;

function onConnected() { isConnected = true; }

hub.disconnect = function() { while(hub.notconnected) { connect(); }
BentOnCoding
  • 27,307
  • 14
  • 64
  • 92
Heather
  • 2,602
  • 1
  • 24
  • 33

3 Answers3

61

This answer is specific to "SignalR version 2" the latest version "ASP.NET Core SignalR" may differ.

SignalR version 2: The JS client attempts to reconnect for a certain time period, which defaults to 110 seconds. You can subscribe to the connection.stateChanged event, and get updates on when the state changes so that you can display it to the user, or validate SignalR's response to different disconnection scenarios.

In my testing, the state was correctly updated to disconnected and reconnecting etc., as you would expect.

More information on signalr connections

function connectionStateChanged(state) {
    var stateConversion = {0: 'connecting', 1: 'connected', 2: 'reconnecting', 4: 'disconnected'};
    console.log('SignalR state changed from: ' + stateConversion[state.oldState]
     + ' to: ' + stateConversion[state.newState]);
}

connection = $.connection(signalR_Endpoint);
connection.stateChanged(connectionStateChanged);
connection.start({ waitForPageLoad: false });
Mazrick
  • 1,149
  • 8
  • 10
  • 7
    I don't think this is totally true. If I lose connection to my server it will eventually give up trying to reconnect and force me to manually restart the connection. I wouldn't say it is always trying to reconnect. – KingOfHypocrites May 01 '14 at 11:53
  • 5
    Note that the possible states are enumerated on `$.signalR.connectionState`, eg `$.signalR.connectionState.connected`. You can see the current usage for `stateChanged` [here](https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client#connectionstatechanged-handlerchange-) – Jon Egerton Jun 26 '14 at 15:31
  • Looking at the client [code](https://github.com/SignalR/SignalR/blob/master/src/Microsoft.AspNet.SignalR.Client.JS/jquery.signalR.transports.longPolling.js), I did not find any reference to a condition which would actually stop reconnecting after a period of time. There is however a backoff calculation that results in longer and longer times between failed re-connection attempts, until there is a successful connection. So I do believe that it will attempt to reconnect "forever" as long as the page JS is alive in the browser. – Mazrick Sep 09 '14 at 14:06
  • 2
    In case anybody arrives here, all the things wrote here only work with the jQuery SignalR plugin, in the official javascript library there is no such event as 'stateChanged": https://learn.microsoft.com/en-us/javascript/api/@microsoft/signalr/hubconnection?view=signalr-js-latest – seekingtheoptimal Jun 18 '21 at 11:19
10

The client is always trying to connect. You don't need to worry about that. There's a reconnected event that you can listen to, in case you want to do something when the connection is successfully reestablished.

EDIT: This changed, the client only tries to reconnect during a certain period of time. After that, you have to catch the disconnection event and manually restart.

nmat
  • 7,430
  • 6
  • 30
  • 43
  • Is there anything special I need to do to implement reconnect? It seems I am not getting Disconnect OR Reconnect events firing. Currently I'm doing: $.connection.hub.disconnect = onDisconnected; $.connection.hub.reconnect = onReconnected; on the client, and have implemented IDisconnect on the hub. – Heather Feb 20 '12 at 20:54
  • @Jon The IDisconnect interface is for server side events and it works fine (make sure that you are using SignalR 0.4). On the client side, the Disconnect event is never triggered because SignalR is never really sure that you are disconnected (this might change in the future I think). The reconnected should work, but I haven't tested it so I can't help you with that. – nmat Feb 21 '12 at 23:38
  • 1
    I've found that the c# client doesn't reconnect if its got to disconnected state. I have to redo hubConnection.Start().Wait(); (I've no idea if this is a good practice or not!) My scenario is a console app on one machine talking to a website on another. If I clean / rebuild the website we go through reconnecting, disconnected and never recover unless I force it manually. – Andiih Jun 17 '14 at 16:15
  • 4
    Not true. If it can't connect for a minute or two it will fully quit. ASP.net signalR pages address this and explain that hub.start does need to be called again in those situations (detectable by hub.disconnected or hub.statechanged) – Josh Sutterfield Apr 12 '16 at 21:26
4

This is my code here :

$.connection.hub.stateChanged(function (state) {
            var stateConversion = { 0: 'connecting', 1: 'connected', 2: 'reconnecting', 4: 'disconnected' };
            console.log('SignalR state changed from: ' + stateConversion[state.oldState]
                + ' to: ' + stateConversion[state.newState]);
        });
Ali Mahmoodi
  • 858
  • 10
  • 14