[英]How to send message to a particular client using 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>();
}
向特定客户端发送消息时,必须从客户端调用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
。要获取ID,您必须使用jQuery,例如,首先您必须在客户端中保存每个客户端的ID
<a id='userid' class="username"></a>
在点击事件中,您可以获取该用户的id
,例如
$("a").on('click',function(){
var touser = $(this).attr('id'))
}
chathub.server.sendMeassage(touser,msg);
这可能不是完整的解决方案,但是您必须这样做。
有好的职位在这里它给出了这个概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.