C# SignalR:检测客户端上的连接状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9334838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SignalR: detect connection state on client
提问by Heather
I've seen how you can trap a disconnection event on the client side with SignalR by binding to the .disconnect event.
我已经看到了如何通过绑定到 .disconnect 事件来使用 SignalR 在客户端捕获断开连接事件。
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(); }
采纳答案by Mazrick
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.
JS 客户端在一定时间段内尝试重新连接,默认为 110 秒。您可以订阅 connection.stateChanged 事件,并在状态更改时获取更新,以便您可以将其显示给用户,或验证 SignalR 对不同断开连接情况的响应。
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 });
回答by nmat
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.
编辑:这已更改,客户端仅在特定时间段内尝试重新连接。之后,您必须捕获断开连接事件并手动重新启动。

