从信号客户端获取返回值

本文关键字:返回值 获取 客户端 信号 | 更新日期: 2023-09-27 18:32:55

我有一个用于向特定客户端发送请求然后获取返回值的 SignalR 方法。我知道这是不可能的,但客户端需要将响应作为单独的消息发送到集线器。

我从中心外部向客户端发送消息:

public String GetResponseFromUser(String userId, String request)
{
    // Use requestId to be sure the response is on this request
    var requestId = Guid.NewGuid().ToString();
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    hubContext.Clients.User(userId).Request(requestId, request);
    // Wait for client to send response to the Hub's Response method
    var response = ...?
    return response;
}

轮毂类

public class MyHub : Hub
{
    public void Response(String requestId, String response)
    {
        // Somehow I want to get the response to the method above
    }
}

如何等待客户端响应并在中心外的方法中使用此响应?

从信号客户端获取返回值

连接集线器后,您必须等待并聆听答案:

hubContext.On("Response", (requestId, response) =>
                {
                    // do something 
                }
               );

当然,你必须保持这种联系。