我有一个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
}
}
如何等待客户端响应并在集线器外的方法中使用此响应?
答案 0 :(得分:3)
连接集线器后,您必须等待并听取答案:
hubContext.On("Response", (requestId, response) =>
{
// do something
}
);
当然,你必须保持这种联系。