SignalR - Checking if a user is still connected

前端 未结 4 814
谎友^
谎友^ 2020-12-09 11:23

I have a hub with method that is called client-side. This method launches a timer with a delegate that runs every 10 seconds. Since it wouldn\'t make sense to keep running t

4条回答
  •  一整个雨季
    2020-12-09 11:45

    Probably the most used solution is to keep a static variable containing users currently connected and overriding OnConnect and OnDisconnect or implementing IDisconnect depending on the version that you use.

    You would implement something like this:

    public class MyHub : Hub
    {
        private static List users = new List();
        public override Task OnConnected()
        {
            users.Add(Context.ConnectionId);
            return base.OnConnected();
        }
    
        //SignalR Verions 1 Signature
        public override Task OnDisconnected()
        {
            users.Remove(Context.ConnectionId);
            return base.OnDisconnected();
        }
    
        //SignalR Version 2 Signature
        public override Task OnDisconnected(bool stopCalled)
        {
            users.Remove(Context.ConnectionId);
            return base.OnDisconnected(stopCalled);
        }
    
        // In your delegate check the count of users in your list.
    }
    

提交回复
热议问题