SignalR:客户端断开连接

时间:2012-03-20 15:04:17

标签: c# model-view-controller signalr disconnect

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

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

我的目标是长轮询运输。

我知道this question但我想对我说清楚一点。

2 个答案:

答案 0 :(得分:9)

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

<击>

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

以上简称SignalR 0.5.x.

来自the official documentation(目前为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();
    }
}

答案 1 :(得分:6)

在SignalR 1.0中,不再实现SignalR.Hubs.IConnected和SignalR.Hubs.IDisconnect,现在它只是对集线器本身的覆盖:

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();
    }
}