Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signalr check if hub already started

I have multiple javascript blocks with signalR functions.

I don't know the order of execution so that i want to start the hub with

$.connection.hub.start();

if it isn't started already.

How can i check if the hub is already started? Starting it multiple times it it throws an error.

like image 568
daniel Avatar asked Feb 25 '13 12:02

daniel


Video Answer


2 Answers

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, 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

like image 77
dpb Avatar answered Sep 28 '22 04:09

dpb


You can check the connection state in each of your functions like:

function doSomething {         if ($.connection.hub.state === $.signalR.connectionState.disconnected) {             $.connection.hub.start().done(function () { myHub.server.myHubMethod(); });         }         else {             myHub.server.myHubMethod();         }     } 
like image 43
Owen Pauling Avatar answered Sep 28 '22 04:09

Owen Pauling