2014-09-21 79 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); 
}