SignalR - Checking if a user is still connected

走远了吗. 提交于 2019-11-30 08:59:10
cillierscharl

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<string> users = new List<string>();
    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)
    {
        return base.OnDisconnected(stopCalled);
    }

    // In your delegate check the count of users in your list.
}

If you save your connectionId in your database, you can check this:

var heartBeat = GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>();

var connectionAlive = heartBeat.GetConnections().FirstOrDefault(c=>c.ConnectionId == connection.ConnectionId);

if (connectionAlive.IsAlive)
{
//Do whatever...
}

From http://forums.asp.net/t/1829432.aspx/1?How+do+I+get+list+of+connected+clients+on+signalr+

IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.notify("Hello world");

So you should be able to get context.Clients.Count.

That post also references the wiki which has lots of good info. You could try using the OnConnected/OnDisconnected examples to track the users, and when you get to zero users stop your call.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!