当连接丢失或有连接状态更改的处理程序时,调用什么SignalR方法



我正在使用SignalR开发一个.NET web应用程序,其中的hub类类似于下面的示例类:

public class ContosoChatHub : Hub
{
public override Task OnConnected()
{
// Add your own code here.
// For example: in a chat application, record the association between
// the current connection ID and user name, and mark the user as online.
// After the code in this method completes, the client is informed that
// the connection is established; for example, in a JavaScript client,
// the start().done callback is executed.
return base.OnConnected();
}
public override Task OnDisconnected()
{
// Add your own code here.
// For example: in a chat application, mark the user as offline, 
// delete the association between the current connection id and user name.
return base.OnDisconnected();
}
public override Task OnReconnected()
{
// Add your own code here.
// For example: in a chat application, you might have marked the
// user as offline after a period of inactivity; in that case 
// mark the user as online again.
return base.OnReconnected();
}
}

更具体地说,我的网络应用程序是连接平板电脑的枢纽。当我关闭平板电脑上的应用程序时,它不会立即触发OnDisconnected任务,耗时长达20秒或更长时间(服务器尝试与客户端重新连接(。

我的问题是,我应该使用哪种方法来检测连接丢失,或者,是否有一个连接状态处理程序可以在连接丢失时触发?

为了防止数据丢失(考虑到平板电脑实际上不是在线的(,我真的需要处理断开连接事件。

非常感谢您的帮助!

稍后编辑:我还在Global.asax文件中包含了以下几行

GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(6);
GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(2);

在Application Start方法中。这些值似乎被保存了,正如调试中所看到的那样,实际上将时间减少了一半,从20-30秒减少到12-14秒,但仍然没有接近2-3秒。

您可以检测到服务器与SignalR客户端的断开连接:

$.connection.hub.disconnected(function () {
alert('Server has disconnected');
});

这是每种方法调用时的官方文档:

当调用OnConnected、OnDisconnected和OnReconnected时

每次浏览器导航到新页面时,都必须有一个新的连接这意味着SignalR将执行OnDisconnected方法,然后是OnConnected方法。SignalR总是创建建立新连接时的新连接ID。

当存在临时SignalR可以自动恢复的连接中断,例如当电缆暂时断开并重新连接时在连接超时之前。OnDisconnected方法被调用当客户端断开连接,SignalR无法自动重新连接,例如当浏览器导航到新页面时。因此给定客户端的可能的事件序列是OnConnected,OnReconnected,OnDisconnected;或OnConnected、OnDisconnected。你看不到的序列OnConnected、OnDisconnected和OnReconnected给定的连接。

在某些情况下不会调用OnDisconnected方法,例如当服务器故障或应用程序域被回收时。什么时候另一台服务器上线或应用程序域完成回收,某些客户端可能能够重新连接并激发OnReconnected事件

最新更新