I am trying to implement request/response paradigm for Websocketsharp library exactly same it works for HttpClient's request/response async behavior. I am trying to achieve it using the async callback as given in below code. I tried to get SendAsync method's OnMessage callback event to wait until the server sends the response. I am able to get the response within the scope of the SendAsync method but as soon as we come out of SendAsync scope it clears out the value of the response.
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;