sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.68k stars 1.66k forks source link

Request/Response paradigm for Websocketsharp library with using Websocket.SendAsync() and OnMessage callback function. #403

Open jitendrajain12 opened 7 years ago

jitendrajain12 commented 7 years ago

We are trying to implement request/response paradigm for Websocketsharp library exactly same it works for HttpClient's request/response async behavior. We are trying to achieve it using the async callback as given in below code. We tried to get SendAsync method's OnMessage callback event to wait until the server sends the response. We are 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;
LordBunny commented 6 years ago

How does this work?

clientResponse = await WSMessageSendSuccess(reqObject, callback);
fr0zeD commented 6 years ago

Hi,

Could you please advise how to implement a proper SendAsync method in order to get the completion response?

Thank you.