2017-04-04 148 views
2

如果我有多個客戶端連接到集線器,我將如何使用JavaScript從客戶端(.aspx)獲取所有連接客戶端的詳細信息。
SendChatMessage()方法中,我必須從客戶端(.aspx)傳遞「who」參數,但是如何才能知道如此多連接的客戶端中特定客戶端的連接標識或用戶名。如何使用SignalR將消息發送到特定客戶端

public class Chathub : Hub 
{ 
    private readonly static ConnectionMapping<string> _connections = 
     new ConnectionMapping<string>(); 

    public void SendChatMessage(string who, string message) 
    { 
     string name = Context.User.Identity.Name; 

     foreach (var connectionId in _connections.GetConnections(who)) 
     { 
      Clients.Client(connectionId).addChatMessage(name + ": "message); 
     } 
    } 

    public override Task OnConnected() 
    { 
     string name = Context.User.Identity.Name; 
     _connections.Add(name, Context.ConnectionId); 
     return base.OnConnected(); 
    } 


public class ConnectionMapping<T> 
{ 
    private readonly Dictionary<T, HashSet<string>> _connections = 
     new Dictionary<T, HashSet<string>>(); 

    public int Count 
    { 
     get 
     { 
      return _connections.Count; 
     } 
    } 

    public void Add(T key, string connectionId) 
    { 
     lock (_connections) 
     { 
      HashSet<string> connections; 
      if (!_connections.TryGetValue(key, out connections)) 
      { 
       connections = new HashSet<string>(); 
       _connections.Add(key, connections); 
      } 

      lock (connections) 
      { 
       connections.Add(connectionId); 
      } 
     } 
    } 

    public IEnumerable<string> GetConnections(T key) 
    { 
     HashSet<string> connections; 
     if (_connections.TryGetValue(key, out connections)) 
     { 
      return connections; 
     } 

     return Enumerable.Empty<string>(); 
    } 
+1

不應該在這個問題上添加C#標籤嗎?它似乎與JavaScript相關。 – evolutionxbox

回答

0

雖然發送消息給特定的客戶端,你必須調用chathub.server.sendMessage()從客戶

public void SendPrivateMessage(string toUserId, string message) 
     { 

      string fromUserId = Context.ConnectionId; 

      var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ; 
      var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId); 

      if (toUser != null && fromUser!=null) 
      { 
       // send to 
       Clients.Client(toUserId).sendMessage(fromUserId, fromUser.UserName, message); 

       // send to caller user as well to update caller chat 
       Clients.Caller.sendMessage(toUserId, fromUser.UserName, message); 
      } 

     } 

Clients.Caller.sendMessage(toUserId, fromUser.UserName, message);注意,這是客戶端的方法,以更新聊天。

在客戶端

然後,調用chathub.server.sendMessage(id,msg) 在那裏你可以傳遞的是specific user id爲了讓你不得不使用jQuery的ID,如首先你要保存每個客戶端的ID在客戶端可以說

<a id='userid' class="username"></a> 

和點擊事件中,你可以得到用戶的id

$("a").on('click',function(){ 

    var touser = $(this).attr('id')) 
    } 

chathub.server.sendMeassage(touser,msg); 

這可能不是完整的解決方案,但你必須做 喜歡這個。

有很好的帖子here它顯示了這個想法。

+0

在SendChatMessage()方法中,通過什麼來代替客戶端的「who」作爲參數。我認爲「誰」正在作爲我的字典(包含連接客戶端的詳細信息的字典)的關鍵字,用於查找具有該關鍵字的ConnectionId。 –

+0

檢查編輯,您必須執行此操作才能實現您的需求。 – MUT

相關問題