How to make SignalR behave gracefully in case of disconnection

萝らか妹 提交于 2019-12-05 22:55:47

How I deal with it:

  • have a isConnected boolean on my client so that whenever I connect, I set it to true, and whenever I disconnect I set it back to false:

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

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!