/// OnConnect callback, the bulk of the work is handled here. void RequestScoresOnConnectCallback(IAsyncResult ar) { RequestScoresState state = (RequestScoresState)ar.AsyncState; // the arguments for the external callback ServerException error = null; ScoresResponse scores = new ScoresResponse(state.level); // handle being unable to connect if (!client.Connected) { error = new ServerException("Unable to connect"); } else { try { // form a request message and send it to the server string request = ScoresRequest.ToJson(state.level); WriteLine(request); // get a response from server and convert back to an object string response = ReadLine(); scores = ScoresResponse.FromJson(response, state.level); } catch (ServerException e) { error = e; } } // report back to user if (state.callback != null) { state.callback.Invoke(scores, error); } // note: even if connection failed, clean up is still necessary DisconnectAsync(ar); }
/// Synchronous score request api method. public ScoresResponse RequestScores(string level) { // Ensure arguments are valid if (level == null) { throw new ArgumentNullException(); } Connect(); // form a request message and send it to the server string request = ScoresRequest.ToJson(level); WriteLine(request); // get a response from server and convert back to an object string response = ReadLine(); ScoresResponse scores = ScoresResponse.FromJson(response, level); Disconnect(); // report back to user return(scores); }