Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...