Skip to main content
 首页 » 编程设计

c#之从 SignalR 客户端获取返回值

2024年08月12日33www_RR

我有一个 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  
                } 
               ); 

当然,您必须保持这种连接。