Search Unity

Best practice to ensure servers reply has been recieved in client WebSocket

Discussion in 'Multiplayer' started by e2000, Sep 15, 2019.

  1. e2000

    e2000

    Joined:
    Sep 10, 2016
    Posts:
    7
    We're working on an online mobile game that uses WebSocket protocol to communicate with a nodeJS server in Unity.

    The logic of the game is based on request/answer routine. Some of the requests, by the way, is very important to be replied by the server like user login request that the client waits till getting the server's reply.

    It's possible that the server reply to the client's request but because of Internet connection issues the reply of the server not been received by the client.

    We are using websocket-sharp and Dispatcher pattern for communicating with the server in Unity.

    Till now In these situations, we start a Coroutine when sending the request and when the server's reply has not been received after seconds, send another request again till we receive an answer.

    Here is a sample code of the current solution :

    Code (CSharp):
    1. public static bool loginAnswerRecieved = false;
    2.  
    3. public IEnumerator CheckLoginRequestAnswerRecieved()
    4. {
    5.     loginAnswerRecieved = false;
    6.  
    7.     yield return new WaitForSeconds(3);
    8.  
    9.     if (!loginAnswerRecieved)
    10.     {
    11.         if(ws.ReadyState == WebSocketState.Open)
    12.         {
    13.             if (loginAnswerCoroutine != null)
    14.             {
    15.                 StopCoroutine(loginAnswerCoroutine);
    16.                 loginAnswerCoroutine = null;
    17.             }
    18.             loginAnswerCoroutine = StartCoroutine(CheckLoginRequestAnswerRecieved());
    19.             if (ws.ReadyState == WebSocketState.Open)
    20.             {
    21.                 SendWsCommand.LoginPlayer();
    22.             }
    23.         }
    24.     }
    25. }
    My question is, is there a better way to do this kind of request/answer? because the number of this kind of requests and the complexity of them is getting bigger and bigger in the progress of the project.

    Thanks.