SignalR: client disconnection

后端 未结 2 1307
傲寒
傲寒 2021-01-05 21:45

How does the SignalR handle client disconnection? Am I right if I state the following?

  • SignalR will detect browser page close/refresh via Javascript event hand
相关标签:
2条回答
  • 2021-01-05 21:56

    If a user refreshes the page, that is treated as a new connection. You are correct that the disconnect is based on a timeout.

    You can handle the Connect/Reconnect and Disconnect events in a Hub by implementing SignalR.Hubs.IConnected and SignalR.Hubs.IDisconnect.

    The above referred to SignalR 0.5.x.

    From the official documentation (currently for 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();
        }
    }
    
    0 讨论(0)
  • 2021-01-05 22:05

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题