如何使用SignalR将消息发送到特定客户端

时间:2017-04-04 11:02:25

标签: javascript c# asp.net signalr

如果我有多个客户端连接到集线器,我如何使用JavaScript从客户端(.aspx)获取所有连接客户端的详细信息。
SendChatMessage()方法中,我必须从客户端(.aspx)传递“who”参数,但是如何在众多连接的客户端中了解特定客户端的连接ID或用户名。

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 个答案:

答案 0 :(得分: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) 在哪里可以传递id specific user 要获得id,你必须使用jQuery,例如,首先你必须在客户端保存每个客户端的id,比如说

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

在点击事件中,您可以获得该用户的id,如

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

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

chathub.server.sendMeassage(touser,msg);

这可能不是完整的解决方案,但你必须这样做。

有好的帖子here显示了这个想法。