Signalr check if hub already started

There are a few ways to approach this problem. The first is to create your own connection status tracking variables, which you set with the connection callback events:

$.connection.hub.start().done(function() { ConnectionStarted = true; })

You can check ConnectionStarted before attempting to start the connection. Unfortunately, this won’t work well, as start() is asynchronous and so many instances could try to start a connection before one has finished and set ConnectionStart to true.

So, working solutions. There are two.

First, have every instance use its own connection object (ie: don’t use the default $.connection.hub, but instead use manual connection creator:

var localConnection = $.hubConnection(); 
var localHubProxy= localConnection.createHubProxy('HubNameHere');

This isn’t great, as most browsers have a limited number of connections allowed per page, and also because it is generally overkill.

IMO, the best solution is to use the single automatic connection with default proxy ($.connection.hub) and look at the connection state (something I just came across). Each connection object has a state:

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

So, in each instance, go for something like this?:

if ($.connection.hub && $.connection.hub.state === $.signalR.connectionState.disconnected) {
  $.connection.hub.start()
}

Also note that when you create a connection, it will sit in state “disconnected” / 4 until start is called on it. Once start is called, the connection will apparently try to reconnect constantly (if it is interrupted) until $.connection.hub.stop() is called (will then go back to state “disconnected”).

Refs:

http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#establishconnection
https://github.com/SignalR/SignalR/wiki

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)