5

SignalR 如何处理客户端断开连接?如果我陈述以下内容,我是对的吗?

  • SignalR 将通过 Javascript 事件处理检测浏览器页面关闭/刷新,并将适当的数据包发送到服务器(通过持久连接);
  • SignalR 不会检测浏览器关闭/网络故障(可能仅通过超时)。

我的目标是长轮询传输。

我知道这个问题,但想对我说清楚一点。

4

2 回答 2

9

如果用户刷新页面,则将其视为新连接。您是正确的,断开连接是基于超时。

SignalR.Hubs.IConnected您可以通过实现和来处理集线器中的连接/重新连接和断开连接事件SignalR.Hubs.IDisconnect

以上提到了 SignalR 0.5.x。

来自官方文档(目前为 v1.1.3):

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();
    }
}
于 2012-03-22T14:03:39.140 回答
6

In SignalR 1.0, the SignalR.Hubs.IConnected and SignalR.Hubs.IDisconnect are no longer implemented, and now it's just an override on the hub itself:

public class Chat : Hub
{
    public override Task OnConnected()
    {
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        return base.OnDisconnected();
    }

    public override Task OnReconnected()
    {
        return base.OnReconnected();
    }
}
于 2013-02-21T10:56:43.897 回答