gpt4 book ai didi

javascript - 如何使用 SignalR 向特定客户端发送消息

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:35 25 4
gpt4 key购买 nike

如果我有多个客户端连接到集线器,我如何使用 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)您可以在其中传递该特定用户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);

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

有好帖here这表明了这个想法。

关于javascript - 如何使用 SignalR 向特定客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com