SignalR - Checking if a user is still connected

前端 未结 4 818
谎友^
谎友^ 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:42

    I have done this way:

    public class PrincipalCommunicator
        {
            public readonly static Lazy _instance = new Lazy(
                    () => new PrincipalCommunicator(GlobalHost.ConnectionManager.GetHubContext())
                );
    
            public List ConnectedUsers { get; set; }
    
            private IHubContext _context;
    
            private PrincipalCommunicator(IHubContext context)
            {
                ConnectedUsers = new List();
                _context = context;
            }
    
            public static PrincipalCommunicatorInstance
            {
                get
                {
                    return _instance.Value;
                }
            }
    
            public bool IsUserConnected(string user)
            {
                return UsuariosConectados.Contains(user);
            }
        }
    
        public class PrincipalHub : Hub
        {
            public override Task OnConnected()
            {
                PrincipalComunicador.Instance.UsuariosConectados.Add(Context.User.Identity.Name);
    
                return base.OnConnected();
            }
    
            public override Task OnDisconnected(bool stopCalled)
            {
                PrincipalComunicador.Instance.UsuariosConectados.Remove(Context.User.Identity.Name);
                return base.OnDisconnected(stopCalled);
            }
        }
    }
    

    This way, all logic to send something to client stays in one place, like the example and you can know if a user is connected anywhere in the code.

提交回复
热议问题