0

I have some trouble figuring this out.

I need to write an API server using WebSocketSharp, and client as well. I got the connection successful with exchanging messages, however, I cannot figure out a way to properly achieve a behavior like this:

1) Client sends a message with request to the server and waits for a response
2) Server handles the request and response with another message
3) Client receives the response and handles the function

The point 2) is already done server side, but I struggle to achieve point 1 and 3 for the following reason: When the client send the message to the server, instead of waiting for a response, it immediately skips to the next code execution.

I managed to achieve a semi-function way, which is done horribly and could go wrong in so many ways (timeout, delays, multiple messages to handle, etc), for example, this is how I handle login to the server:

Class Connection {

    private bool auth = false;
    public string user, pwd;
    WebSocket ws = new WebSocket("ws://localhost:1111");

    public void Start() {
        ws.OnMessage += Ws_OnMessage;
        ws.Connect();
    }
    public void Ws_OnMessage(object sender, MessageEventArgs e) {
        string[] decode = e.Data.Split(','); //splitting the server response
        if (decode[0].Contains("auth") && decode[1].Contains("accepted")) { auth = true; } //handle request
    }
    public bool login()
    {
        ws.Send($"auth,{user},{pwd}"); //client send request to login to server
        Thread.Sleep(3000); //wait response from server handled over Ws_onMessage
        if (auth) { return true; } else { return false; } //check the response based on bool
    }
}

This in "perfect" conditions works, but we all know nothing's perfect, and this will be subjects to many failures.

My question, how do I achieve this behavior properly? Is there a proper way?

  • You should implement an awaitable receive. Unfortunately, it does not appear that the websocket-sharp library offers a way to receive using a TPL-compatible async method. So you have to use the `OnMessage` event with `await`. See duplicate for how to do that. – Peter Duniho Jul 28 '21 at 19:58
  • @PeterDuniho I've checked the thread you linked, but, it's not related to sockets, I don't actually know what to do with it – Fede Kindred Jul 28 '21 at 20:01
  • _"it's not related to sockets"_ -- no, but it's related to the C# feature `event`, which is actually what your question is about, whether in the context of a socket or some other object. _"I don't actually know what to do with it"_ -- you should use the advice in the duplicate to implement a way for you to use `await` with the `OnMessage` event that you are handling. – Peter Duniho Jul 28 '21 at 21:08

0 Answers0