Checking if a group is an empty SignalR?

In OnConnected, the method client is added to the group with its name (the group contains the entire client identifier), then its name is added to the list if it does not exist.

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 the OnDisconnected method, I try to check if a group is empty to remove an item from the list. But after removing the last compound, the group is not equal to zero.

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);
}

Is it possible to check an empty group?

+4
source share
1 answer

I think it will be a little late to answer your question, maybe you already forgot: d

I solved the problem as follows, using a dictionary that contains the 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);
}
+2

All Articles