我們討論不同的替代方案,以支持保活「喜歡」功能對於長輪詢;然而,由於投票的覆蓋時間有多長,在不影響絕大多數用戶的情況下實施起來並不容易。隨着我們繼續辯論「正確」的解決方案,我將爲您提供一項解決方案,以便在長輪詢客戶端中檢測網絡故障(如果絕對需要)。
創建一個服務器的方法,讓我們稱它爲平:
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);
}
});
希望這有助於!
感謝您的回答。檢測客戶端上的斷開連接對於我們的應用程序的工作是非常必要的,所以我認爲我們會像您所建議的那樣使用某種類型的定期ping。謝謝! – xsov