加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – 检查组是否为空SignalR?

发布时间:2020-12-16 09:40:50 所属栏目:asp.Net 来源:网络整理
导读:在OnConnected方法中,客户端以其名称(组包含所有客户端ID)添加到组中,如果它不存在,则将其名称添加到列表中. static Liststring onlineClients = new Liststring(); // list of clients namespublic override Task OnConnected(){ Groups.Add(Context.Connec
在OnConnected方法中,客户端以其名称(组包含所有客户端ID)添加到组中,如果它不存在,则将其名称添加到列表中.

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

在OnDisconnected方法中,我正在尝试测试该组是否为空以从列表中删除元素.但删除最后一次连接后,该组不为空.

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

我可以查看空组吗?

解决方法

我想这对你的问题有点迟了,也许你已经忘记了:d

我使用包含组名(User.Identity.Name)及其客户端号的字典解决了我的问题.

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,out count))
    {
        if (count == 1)//if group contains only 1client
            onlineClientCounts.Remove(IdentityName);
        else
            onlineClientCounts[IdentityName] = count - 1;
    }

    return base.OnDisconnected(stopCalled);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读