即时检测 SignalR Hub 客户端断开连接

6
SignalR Hub的OnDisconnected在服务器端何时被触发,对于未调用Stop方法就崩溃或关闭的.net客户端,仍然可以被触发。
我正在使用SignalR .NET客户端进行测试,而非JavaScript客户端。 如果在客户端上调用Stop方法,则Hub将立即触发OnDisconnected方法。
但是,如果关闭客户端或结束进程,则Hub只有在大约10秒后才会触发OnDisconnected方法。
如何立即检测客户端已断开连接?
2个回答

5

阅读了这里的SignalR事件文档后,我注意到了以下内容:

当一个连接处于非活动状态时,服务器会定期向客户端发送一个保持活动数据包。截至本文编写日期,默认频率为每10秒一次。

文档中还有一节描述如何更改保持活动设置。

protected void Application_Start(object sender, EventArgs e)
{
    // Make long polling connections wait a maximum of 110 seconds for a
    // response. When that time expires, trigger a timeout command and
    // make the client reconnect.
    GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(110);

    // Wait a maximum of 30 seconds after a transport connection is lost
    // before raising the Disconnected event to terminate the SignalR connection.
    GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(30);

    // For transports other than long polling, send a keepalive packet every
    // 10 seconds. 
    // This value must be no more than 1/3 of the DisconnectTimeout value.
    GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);

    RouteTable.Routes.MapHubs();
}

因此,您可以考虑减少该值,以便更快地接收有关客户端连接中断的通知。

嗨,Jason,感谢提供信息。但是根据我的测试,KeepAlive 只会影响 Hub 客户端代理时间来引发 StateChanged 事件。我已经尝试在服务器端将 ConnectionTimeout 设置为 6 秒和 KeepAlive 设置为 2 秒,但对于 Hub OnDisconnected 方法没有任何影响。 - John Hpa

3

如何立即检测客户端是否断开连接?

由于TCP的工作方式,除非您尝试向该客户端发送数据,否则无法立即检测到其是否已断开连接。正如@JasonEvans的答案所解释的那样,SignalR默认每十秒发送数据(一个“保持活动”消息)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接