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?