Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR: detect connection state on client

Tags:

c#

signalr

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(); } 
like image 208
Heather Avatar asked Feb 17 '12 20:02

Heather


People also ask

How do I check if my SignalR is reconnecting?

To test reconnect after the server goes down use iisreset. To simulate client connection dropping (good luck) pull the network cable :) Pulling the network cable won't accurately simulate a client connection dropping when you're using Azure SignalR Service.

How long do SignalR connections stay open?

The default keepalive timeout period is currently 20 seconds. If your client code tries to call a Hub method while SignalR is in reconnecting mode, SignalR will try to send the command. Most of the time, such attempts will fail, but in some circumstances they might succeed.


1 Answers

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 }); 
like image 146
Mazrick Avatar answered Sep 28 '22 03:09

Mazrick