2014-09-21 109 views
4

在OnConnected方法中,客户端以其名称(组包含所有客户端ID)添加到组中,然后如果名称不存在,则将其名称添加到列表中。检查组是否为空SignalR?

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

我可以检查空组吗?

+0

问题不清楚,什么是“组”类型? – 2014-09-21 10:04:13

+1

SignalR不提供任何API来查询组是否有任何活动客户端。没有什么能够阻止你在OnConencted和OnDisconnected中手动跟踪它。 – halter73 2014-09-22 19:55:33

回答

2

我认为这将是一个有点晚答复你的问题,也许你已经忘了: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, 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); 
}