我想要用户 1 向用户 2 发送消息,但要做到这一点,我必须获取用户 2 连接 ID
因此,当我每次尝试发送消息时,它都会获取用户 1 连接 ID 并将其添加到此代码中
public async Task SendMessage(string targetConnectionId, string message)
{
//await Clients.All.SendAsync("ReceiveMessage", targetConnectionId, message);
await Clients.User(user).SendAsync("ReceiveMessage", targetConnectionId, message);
}
那么我怎样才能获取用户2的连接ID,这样我就可以从用户1向用户2发送消息给他
测试结果
测试代码
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections.Features;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace SignalRMiddleawre.Hubs
{
[Authorize]
public partial class MainHub : Hub
{
#region Connection
/// <summary>
/// Use ConcurrentDictionary to save connected users's id and connectionId
/// </summary>
private static ConcurrentDictionary<string, List<string>>? ConnectedUsers = new ConcurrentDictionary<string, List<string>>();
/// <summary>
/// OnConnectedAsync method
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
///
public override async Task OnConnectedAsync()
{
string? userid = Context.User?.Identity?.Name;
if (userid == null || userid.Equals(string.Empty))
{
Trace.TraceInformation("user not loged in, can't connect signalr service");
return;
}
Trace.TraceInformation(userid + "connected");
// save connection
List<string>? existUserConnectionIds = null;
ConnectedUsers?.TryGetValue(userid, out existUserConnectionIds);
if (existUserConnectionIds == null)
{
existUserConnectionIds = new List<string>();
}
existUserConnectionIds.Add(Context.ConnectionId);
ConnectedUsers?.TryAdd(userid, existUserConnectionIds);
await base.OnConnectedAsync();
}
/// <summary>
/// OnDisconnectedAsync
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public override async Task OnDisconnectedAsync(Exception? exception)
{
string? userid = Context.User?.Identity?.Name;
// save connection
List<string>? existUserConnectionIds= new List<string>() ;
ConnectedUsers?.TryGetValue(userid, out existUserConnectionIds);
existUserConnectionIds?.Remove(Context.ConnectionId);
if (existUserConnectionIds?.Count == 0)
{
List<string> garbage;
ConnectedUsers?.TryRemove(userid, out garbage);
}
await base.OnDisconnectedAsync(exception);
}
#endregion
#region Message
public async Task SendToSingleUser(string userid, string message)
{
List<string>? existUserConnectionIds = null;
ConnectedUsers?.TryGetValue(userid, out existUserConnectionIds);
if (existUserConnectionIds == null)
{
existUserConnectionIds = new List<string>();
}
existUserConnectionIds.Add(Context.ConnectionId);
ConnectedUsers?.TryAdd(userid, existUserConnectionIds);
string? fromUser = Context.User?.Identity?.Name;
string? ToUser = userid;
await Clients.Clients(existUserConnectionIds).SendAsync("ReceiveMessage_SpecificUser", fromUser,ToUser, message);
}
#endregion
}
}