SignalR: detect connection state on client

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

I've seen how you can trap a disconnection event on the client side with SignalR by binding to the .disconnect event.

Now that I've done this, I want to put the client into a "waiting to reconnect cycle" where it continually tries to connect until it succeeds or the user cancels out. Does the hub expose a connection state property? I'm thinking something like (pseudo code)

var isConnected;  function onConnected() { isConnected = true; }  hub.disconnect = function() { while(hub.notconnected) { connect(); } 

回答1:

The JS client attempts to reconnect for a certain time period, which defaults to 110 seconds. You can subscribe to the connection.stateChanged event, and get updates on when the state changes so that you can display it to the user, or validate SignalR's response to different disconnection scenarios.

In my testing, the state was correctly updated to disconnected and reconnecting etc., as you would expect.

More information on signalr connections

function connectionStateChanged(state) {     var stateConversion = {0: 'connecting', 1: 'connected', 2: 'reconnecting', 4: 'disconnected'};     console.log('SignalR state changed from: ' + stateConversion[state.oldState]      + ' to: ' + stateConversion[state.newState]); }  connection = $.connection(signalR_Endpoint); connection.stateChanged(connectionStateChanged); connection.start({ waitForPageLoad: false }); 


回答2:

The client is always trying to connect. You don't need to worry about that. There's a reconnected event that you can listen to, in case you want to do something when the connection is successfully reestablished.

EDIT: This changed, the client only tries to reconnect during a certain period of time. After that, you have to catch the disconnection event and manually restart.



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