我正在尝试为 Websocketsharp 库实现请求/响应范例,它与 HttpClient 的请求/响应异步行为完全相同。我正在尝试使用下面代码中给出的异步回调来实现它。我试图让 SendAsync 方法的 OnMessage 回调事件等到服务器发送响应。我能够在 SendAsync 方法的范围内获得响应,但是一旦我们离开 SendAsync 范围,它就会清除响应的值。
string clientResponse = null;
var response = Task.Run(() => objWSClient.SendAsync(stream, Convert.ToInt32(stream.Length), (async (completed) =>
{
if (completed)
{
clientResponse = await WSMessageSendSuccess(reqObject, callback);
// Websocket response is flushed to the console window, but when it leaves the scope, it doesn't hold the response out of the SendAsync() scope.
Console.WriteLine(clientResponse);
}
else
{
WSMessageSendFail(reqObject);
clientResponse = "Failure to send Message";
}
})));
while (response.Status != TaskStatus.RanToCompletion)
{
Task.Delay(10000).Wait();
}
response.Wait();
// As soon as we leave scope of WebSocket.SendAsync() method, it clears the client response variable value.
// variable name : clientResponse;, it also works same with static property/variable.
return clientResponse;