// Get a message from the server, choose what action to executed depending if it is a request, a response, notification or an error // If it is a request, use the callback when the request is finished public void HandleMessage(string json, SuccessRequest onSuccessRequest, ErrorRequest onErrorRequest) { //Debug.Log("Message: " + json); var data = Json.Deserialize(json) as Dictionary <string, object>; if (data.ContainsKey("error")) // Response error from a request this client made to the server { var idAction = data["id"].ToString(); var errorData = data["error"] as Dictionary <string, object>; int code = Convert.ToInt32(errorData["code"]); string errorMessage = errorData["message"].ToString(); // Check if there is data inside the error Dictionary <string, object> dataError = null; if (errorData.ContainsKey("data")) { dataError = errorData["data"] as Dictionary <string, object>; } _handler.handleError(idAction, code, errorMessage, dataError); } else if (data.ContainsKey("result")) // result the server is sending to this client, from a request this client made to the server previously { var idAction = data["id"].ToString(); object result = data["result"]; _handler.handleResponse(idAction, result); } else // request message or notification. A request the server is asking to this client, or a notification the server is sending to this client { string method = data["method"].ToString(); Dictionary <string, object> param = null; if (data.ContainsKey("params")) { param = Json.Deserialize(data["params"].ToString()) as Dictionary <string, object>; } string idAction = null; if (data.ContainsKey("id")) // if it have id, it is a request { idAction = data["id"].ToString(); try{ var result = _handler.handleRequest(method, param); onSuccessRequest(result, idAction); }catch (Exception e) { onErrorRequest(idAction, new Dictionary <string, object>(), e); } } else // Notification { _handler.handleNotification(method, param); } } }
protected virtual void OnSuccessRequest(ClientRequestEventArgs e) { SuccessRequest?.Invoke(this, e); }