Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether the group is empty SignalR?

In OnConnected method client is added to the group with his name (group contains all of the client id) then his name is added to the list if it is not exists.

static List<string> onlineClients = new List<string>(); // list of clients names

public override Task OnConnected()
{
    Groups.Add(Context.ConnectionId, Context.User.Identity.Name);

    if (!onlineClients.Exists(x => x == Context.User.Identity.Name))
    {
        onlineClients.Add(Context.User.Identity.Name);
    }

    return base.OnConnected();
}

In OnDisconnected method I'm trying to test whether the group is empty to remove element from list. But after removing last connection the group is not null.

public override Task OnDisconnected(bool stopCalled)
{
    if (stopCalled)
    {
        // We know that Stop() was called on the client,
        // and the connection shut down gracefully.

        Groups.Remove(Context.ConnectionId, Context.User.Identity.Name);

        if (Clients.Group(Context.User.Identity.Name) == null)
        {
            onlineClients.Remove(Context.User.Identity.Name);
        }

    }
    return base.OnDisconnected(stopCalled);
}

Can I check for empty group?

like image 362
Lev Alefirenko Avatar asked Sep 21 '14 08:09

Lev Alefirenko


1 Answers

I think this will be a little late reply to your question, maybe you've already forgotten :d

I solved the my problem as follows using a dictionary that holds group name(User.Identity.Name) and its client numbers.

private static Dictionary<string, int> onlineClientCounts  = new Dictionary<string, int>();

public override Task OnConnected()
{
    var IdentityName = Context.User.Identity.Name;
    Groups.Add(Context.ConnectionId, IdentityName);

    int count = 0;
    if (onlineClientCounts.TryGetValue(IdentityName, out count))
        onlineClientCounts[IdentityName] = count + 1;//increment client number
    else
        onlineClientCounts.Add(IdentityName, 1);// add group and set its client number to 1

    return base.OnConnected();  
}

public override Task OnDisconnected(bool stopCalled)
{
    var IdentityName = Context.User.Identity.Name;
    Groups.Remove(Context.ConnectionId, IdentityName);

    int count = 0;
    if (onlineClientCounts.TryGetValue(IdentityName, out count))
    {
        if (count == 1)//if group contains only 1client
            onlineClientCounts.Remove(IdentityName);
        else
            onlineClientCounts[IdentityName] = count - 1;
    }

    return base.OnDisconnected(stopCalled);
}
like image 160
agit Avatar answered Oct 11 '22 18:10

agit