问题
My application will often be used under fucked up corporate networks (proxy, firewalls, etc.) so I can not rely on sockets and long-polling is practically my only option. Here is my biggest problem with long-polling:
- Long-polling is disconnected at some point of time
- I automatically reconnect (accoring to documentation)
- User clicks something that causes hub method call but connection is not established yet - error happens.
Is there any way to synchronize hub method call and reconnection like:
- I call hub method
- SignalR sees connection is not ready yet
- It waits till connection is ready and calls a hub method afterall
For now I don't see such an oportunity and it seems like my only option is to switch to ajax calls which is sad.
回答1:
How I deal with it:
have a
isConnected boolean
on my client so that whenever I connect, I set it totrue
, and whenever I disconnect I set it back tofalse
:$.connection.hub.start().fail((err) => { alert(err); }).done(() => this.isConnected = true); $.connection.hub.disconnected(() => { this.isConnected = false; }); $.connection.hub.reconnected(() => { this.isConnected = true; });
now, right before I make the call to a hub method, I check if
isConnected
is true. If not, I attempt start the hub connection:$("#serverButton").click(function(){ if(this.isConnected==false) $.connection.hub.start(); $.connection.hub.server.serverMethod();
})
This is how I handle such situations right now. Hope this helps. Best of luck!
UPDATE: There actually exists a property on $.connection.hub
called state
that you can access at every point during the connection.
So you can skip the step of having your own variable (though I still use it just to be sure) by checking $.connection.hub.state
.
$.connection.connectionState
Object {connecting: 0, connected: 1, reconnecting: 2, disconnected: 4}
The output from $.connection.hub.state
is an integer from the ones above, but you can do something like this: $.connection.hub.state == $.signalR.connectionState.connected
and you can have booleans.
Easier, but you still have to check this every time you make a call to a hub method.
回答2:
Your client can take a look if currently connected and do things accordingly. Use connection object:
$.signalR.connectionState
Object {connecting: 0, connected: 1, reconnecting: 2, disconnected: 4}
And do thing based on current state:
if ($.connection.hub && $.connection.hub.state === $.signalR.connectionState.connected) {
// I am online
}
Waiting for connection to be established:
$.connection.hub.start().done(function() {
// Now the connection is established
}
Waiting for your method to finish:
yourHub.server.yourMethod(param1, param2).done(function() {
// Now yourMethod is finished
}
来源:https://stackoverflow.com/questions/32310680/how-to-make-signalr-behave-gracefully-in-case-of-disconnection