【发布时间】:2022-02-24 22:12:51
【问题描述】:
我想向特定客户端发送数据。我有 Asp.net core web api(.Net-6.0) 控制器,它有一个集线器帮助调用远程 Worker 服务上的方法。 Hub 正在主动向特定的 Worker 客户端逐一发送调用。 如何以及在哪里保留 connectionId 和相应的 WorkerID,这样当 MiniAppController 收到请求时,它会使用 hubContext 通过正确的连接触发请求。代码示例是:
public class ChatHub : Hub
{
private readonly ILogger<ChatHub> _logger;
public ChatHub(ILogger<ChatHub> logger)
{
_logger = logger;
}
public async Task HandShake(string workerId, string message)
{
HubCallerContext context = this.Context;
await Clients.Caller.SendAsync("HandShake", workerId, context.ConnectionId);
}
public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
_logger.LogInformation($"1.Server: Client disconnected and left the group..............");
await base.OnDisconnectedAsync(exception);
}
}
Webapi 控制器:
[Route("api/[controller]")]
[ApiController]
public class MiniAppController : ControllerBase
{
private readonly IHubContext<ChatHub> _chatHubContext;
private readonly ILogger<ChatHub> _logger;
public MiniAppController(IHubContext<ChatHub> chatHubContext)
{
_chatHubContext = chatHubContext;
}
[HttpGet]
public async Task<ActionResult<CheckoutInfo>> Checkout(string comID, string parkServerID, string parkLotID, string parkID, string miniAppID, string miniUserID, string sign)
{
string workerId = comID + parkServerID + parkLotID;//extracted from the method arguments
***//how to use workerId to send to a specific client???***
......
}
}
作为 SignalR 客户端的工作器服务,我可以有多个工作器:
public class Worker1 : BackgroundService
{
private readonly ILogger<Worker1> _logger;
private HubConnection _connection;
public Worker1(ILogger<Worker1> logger)
{
_logger = logger;
_connection = new HubConnectionBuilder()
.WithUrl("http://localhost:5106/chatHub")
.WithAutomaticReconnect()
.Build();
_connection.On<string, string>("HandShakeAck", HandShakeAck);
_connection.On<string, string>("ReceiveMessage", ReceiveMessage);
_connection.On<CheckoutRequest>("Checkout", Checkout);
}
public Task Checkout(CheckoutRequest checkoutRequest)
{
//send Checkoutinfo back
CheckoutInfo checkoutInfo = new CheckoutInfo();
_connection.InvokeAsync("ReceiveCheckoutInfo", workerId, checkoutInfo);
return Task.CompletedTask;
}
}
请帮忙。谢谢
【问题讨论】:
-
查看我对类似问题的回答。我相信这是你需要的。 stackoverflow.com/a/71217523/14717905
-
是的,我一直在考虑这样做,就像您对该帖子的回答一样。问题是 HubConnectionBuilder() 和 OnConnectedAsync() 没有可用于在建立连接时将 workerId 发送到服务器的参数。我可以通过调用 HandSake() 开始构建 workerId 和 connectionId 之间的映射。但不觉得这是一个好方法。有没有更好的方法来做到这一点?(比如在客户端建立连接的过程中这样做)
标签: c# signalr signalr-hub webapi .net-6.0