我们已经讨论了不同的替代方案,以支持长时间轮询的“赞”功能.但是,由于调查在后台进行了多长时间,因此在不影响绝大多数用户的情况下实施起来并不容易.在我们继续争论“正确”解决方案的过程中,我将为您解决一个问题,以便在长轮询客户端中检测网络故障(如果绝对需要).
创建一个服务器方法,将其称为ping:
public class MyHub : Hub
{
public void Ping()
{
}
}
现在在客户端上创建一个间隔,在该间隔中您将“ ping”服务器:
var proxy = $.connection.myHub,
intervalHandle;
...
$.connection.hub.disconnected(function() {
clearInterval(intervalHandle);
});
...
$.connection.hub.start().done(function() {
// Only when long polling
if($.connection.hub.transport.name === "longPolling") {
// Ping every 10s
intervalHandle = setInterval(function() {
// Ensure we're connected (don't want to be pinging in any other state).
if($.connection.hub.state === $.signalR.connectionState.connected) {
proxy.server.ping().fail(function() {
// Failed to ping the server, we could either try one more time to ensure we can't reach the server
// or we could fail right here.
TryAndRestartConnection(); // Your method
});
}
}, 10000);
}
});
希望这可以帮助!