如何使用SignalR将消息发送到特定客户端
如果我有多个客户端连接到集线器,我将如何使用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>();
}
虽然发送消息给特定的客户端,你必须调用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它显示了这个想法。
在SendChatMessage()方法中,通过什么来代替客户端的“who”作为参数。我认为“谁”正在作为我的字典(包含连接客户端的详细信息的字典)的关键字,用于查找具有该关键字的ConnectionId。 –
检查编辑,您必须执行此操作才能实现您的需求。 – MUT
不应该在这个问题上添加C#标签吗?它似乎与JavaScript相关。 – evolutionxbox