コード例 #1
0
	void onAuthenticationFinished(HTTPRequest req, HTTPResponse res) {
		JsonReader json = new JsonReader (res.DataAsText);
		json.SkipNonMembers = true;
		// deserialize
		Token token = JsonMapper.ToObject<Token> (json);
		// authentication correct
		if (token != null) {
			if (token.success) {
				// save to player preferences
				PlayerPrefs.SetString ("token", token.token);
				PlayerPrefs.SetString ("username", token.username);
				PlayerPrefs.Save();
				// when we finish the authentication process, load the main menu
				utils.loadScene("MainMenu");
			}
			else {
				Debug.Log(token.message);
				_dispatcher.Dispatch("show_error_register_login");
			}
		}
		// authentication erroneous, show error message
		else {
			//TODO: show error message
		}
	}
コード例 #2
0
ファイル: ConfigManager.cs プロジェクト: Keyj1n/BattlePong
    private void HandleConfigResponse(HTTPResponse response) {
      Dictionary<string, object> data;
      try {
        data = ParseResponse(response);
      }
      catch(Exception) {
        return;
      }

      if(data == null) {
        return;
      }

      Utils.LogDebug("Received config response");

      if(response.headers != null && response.headers.ContainsKey("ETAG")) {
        string etag = response.headers["ETAG"];
        configId = etag.Substring(3, etag.Length - 4);
      }

      ZoneManager.Instance.ResetZones((List<object>)data["zones"]);
      adSourceTtl = (long)data["adSourceTtl"];
      serverTimestamp = (long)data["serverTimestamp"];

      RequestAdSources();

      _requestingConfig = false;
    }
コード例 #3
0
ファイル: HTTProxy.cs プロジェクト: lscyane/KCBr
 public  SessionInfo()
 {
     Ignore = false;
     BypassServerRequest = false;
     Response = new HTTPResponse();
     Request = new HTTPRequest();
 }
コード例 #4
0
    protected override void UpdateContentData(HTTPClient client,
        HTTPResponse response)
    {
      uint connectionID = client.ConnectionID;
      ulong length =
        Bindings._URLClientGetPendingResponseContentLength(connectionID);

      // no data pending?
      if (length <= 0)
      {
        return;
      }

      ulong copied;

      // buffer read pending data
      do
      {
        if (_contentDataBuffer == null)
        {
          _contentDataBuffer = new byte[RESPONSE_BUFFER_SIZE];
        }

        copied = Bindings.URLClientMovePendingResponseContent(connectionID,
            _contentDataBuffer, RESPONSE_BUFFER_SIZE);

        if (copied <= (ulong)0)
        {
          break;
        }

        OnDidReceiveData(response, _contentDataBuffer, copied);
        response.receivedContentLength += copied;
      } while (copied == RESPONSE_BUFFER_SIZE);
    }
コード例 #5
0
	void processGameEnd(HTTPRequest req, HTTPResponse res) {
		// deserialize json
		GameModel game = JsonMapper.ToObject<GameModel> (res.DataAsText);
		// update game
		if (!string.IsNullOrEmpty(((GameModel)game)._id)) {
			_dispatcher.Dispatch("update_game", game);
		}
	}
コード例 #6
0
 public void HandleRequest(HTTPRequest request, HTTPResponse response)
 {
     if (_redirectionType == WoopsaRedirectionType.Temporary)
         response.SetStatusCode((int)HTTPStatusCode.TemporaryRedirect, "Temporary redirect");
     else if (_redirectionType == WoopsaRedirectionType.Permanent)
         response.SetStatusCode((int)HTTPStatusCode.Moved, "Permanent redirection");
     response.SetHeader("Location", _targetLocation);
 }
コード例 #7
0
	void endAPICall(HTTPRequest req, HTTPResponse res) {
		// deserialize json
		question = JsonMapper.ToObject<QuestionModel> (res.DataAsText);
		// save questionId
		PlayerPrefs.SetString ("questionId", question._id);
		// end spinning
		callingAPI = false;
	}
コード例 #8
0
        void OnAuthRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            AuthRequest = null;
            string failReason = string.Empty;

            switch (req.State)
            {
                // The request finished without any problem.
                case HTTPRequestStates.Finished:
                    if (resp.IsSuccess)
                    {
                        Cookie = resp.Cookies != null ? resp.Cookies.Find(c => c.Name.Equals(".ASPXAUTH")) : null;

                        if (Cookie != null)
                        {
                            HTTPManager.Logger.Information("CookieAuthentication", "Auth. Cookie found!");

                            if (OnAuthenticationSucceded != null)
                                OnAuthenticationSucceded(this);

                            // return now, all other paths are authentication failures
                            return;
                        }
                        else
                            HTTPManager.Logger.Warning("CookieAuthentication", failReason = "Auth. Cookie NOT found!");
                    }
                    else
                        HTTPManager.Logger.Warning("CookieAuthentication", failReason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                        resp.StatusCode,
                                                        resp.Message,
                                                        resp.DataAsText));
                    break;

                // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
                case HTTPRequestStates.Error:
                    HTTPManager.Logger.Warning("CookieAuthentication", failReason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
                    break;

                // The request aborted, initiated by the user.
                case HTTPRequestStates.Aborted:
                    HTTPManager.Logger.Warning("CookieAuthentication", failReason = "Request Aborted!");
                    break;

                // Ceonnecting to the server is timed out.
                case HTTPRequestStates.ConnectionTimedOut:
                    HTTPManager.Logger.Error("CookieAuthentication", failReason = "Connection Timed Out!");
                    break;

                // The request didn't finished in the given time.
                case HTTPRequestStates.TimedOut:
                    HTTPManager.Logger.Error("CookieAuthentication", failReason = "Processing the request Timed Out!");
                    break;
            }

            if (OnAuthenticationFailed != null)
                OnAuthenticationFailed(this, failReason);
        }
コード例 #9
0
    private void OnRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        var json = JSON.Parse(response.DataAsText);

        for (int i = 0; i < json.Count; i++)
        {
            itemlist.Add(new Item(
                 json[i]["code"]
                 , json[i]["name"]
                 , json[i]["damage"]
                 , json[i]["price"]
                 , json[i]["avatar"]
                 , json[i]["itemCategoryId"]
                 , json[i]["id"]
                 , json[i]["categoryId"]
                 ));
            //kiem tra xem sung da mua chua
            itemlist [i].bought = 0;
            //Debug.Log ("so sanh item ; " + json [i] ["id"]);
            for(int k = 0; k<GetUserId.itemid.Count; k++){
            //	Debug.Log ("so sanh voi :" + GetUserId.itemid [k]+ "va ;"+ json[i]["id"]);
                if (json [i] ["id"].ToString().Trim('"').Equals( GetUserId.itemid [k].ToString())) {
                    itemlist [i].bought = 1;
                    Debug.Log ("trung nhau giua ;"+ GetUserId.itemid[k] +"va :"+ json[i]["name"]);

                }
            }
            GameObject bullet3;
            if (itemlist [i].bought == 1) {
                 bullet3 = (GameObject)Instantiate (itemprefab2, itemPo [i].transform.position, Quaternion.identity);
            } else {
                 bullet3 = (GameObject)Instantiate (itemprefab1, itemPo [i].transform.position, Quaternion.identity);
            }

            Transform[] allChildren = bullet3.transform.GetComponentsInChildren<Transform>();
            foreach (Transform t in allChildren)
            {
                if (t != null && t.gameObject.name == "Wp")
                {

                    new HTTPRequest(new Uri(json[i]["avatar"]), (request, res)
                    =>
                    {
                        var texture = new Texture2D(0, 0);
                      //  Debug.Log("red.data = "+ res);
                        texture.LoadImage(res.Data);
                      t.GetComponent<SpriteRenderer>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    }
                    ).Send();
                }
            }
            bullet3.transform.SetParent(GameObject.Find("Weapons").transform);
            bullet3.transform.position = itemPo[i].transform.position;
            bullet3.transform.localScale = new Vector3 (0.9f, 0.9f, 0.9f);
        }
    }
コード例 #10
0
    private void OnRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        var json = JSON.Parse(response.DataAsText);

           // Debug.Log(response.DataAsText);
        for (int i = 0; i < json ["item"].Count; i++) {
            itemid.Add(json["item"][i]);
            //Debug.Log ("item la " + itemid[i]);
        }
    }
コード例 #11
0
	void responseReady(HTTPRequest req, HTTPResponse res) {
		responseRdy = true;
		// deserialize json
		game = JsonMapper.ToObject<GameModel> (res.DataAsText);
		// send analytics
		if (!correctAnswer) {
			GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus.GAProgressionStatusComplete, "match", "turn_" + (game.turn - 1));
		}
		// call process response to sync with wait
		processResponse ();
	}
コード例 #12
0
	void questionReady(HTTPRequest req, HTTPResponse res) {
		float delay = ((Time.time - startTime) < (Properties.starQuestionDelay - Properties.delayQuestionStart)) ? Properties.starQuestionDelay : Properties.delayQuestionStart;
		// parse response
		question = JsonMapper.ToObject<QuestionModel> (res.DataAsText);
		// save questionId
		PlayerPrefs.SetString ("questionId", question._id);
		// deay action and launch question
		Utils.delayAction (this, () => {
			// dispatch event to start question
			_dispatcher.Dispatch ("question_loaded", question);
			// fadeout panel
			Utils.fadeOutPanel (this, panel, Properties.starQuestionFadeInOutDuration, executeQuestion);
		}, 
		delay);
	}
コード例 #13
0
    private void OnRequestFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        var json = JSON.Parse(response.DataAsText);

        if (response.StatusCode == 200)
        {
            Debug.Log(json["userId"].Value);
            PlayerPrefs.SetString("token", json["id"].Value);
            PlayerPrefs.Save();
            PlayerPrefs.SetString("UserId", json["userId"].Value);
            PlayerPrefs.Save();
            AutoFade.LoadLevel("lobbyScreen", 1.2f);
        }
        else
        {
            //   Debug.Log("Login failed !");
        }
    }
コード例 #14
0
 void onAuthenticationFinished(HTTPRequest req, HTTPResponse res)
 {
     JsonReader json = new JsonReader (res.DataAsText);
     json.SkipNonMembers = true;
     // deserialize
     Token token = JsonMapper.ToObject<Token> (json);
     // authentication correct
     if (token != null) {
         // save to player preferences
         PlayerPrefs.SetString ("token", token.token);
         PlayerPrefs.SetString ("username", token.username);
         // when we finish the authentication process, load the main menu
         Application.LoadLevel("MainMenu");
     }
     // authentication erroneous, show error message
     else {
         //TODO: show error message
     }
 }
コード例 #15
0
    private void OnCharacterFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        var json = JSON.Parse(response.DataAsText);

        for (int i = 0; i < json.Count; i++)
        {
            characteritemlist.Add(new CharacterItem(
                json[i]["code"]
                , json[i]["name"]
                , json[i]["strength"]
                , json[i]["speed"]
                , json[i]["avatar"]
                , json[i]["description"]
                , json[i]["id"]
                ));
            var bullet3 = (GameObject)Instantiate(characteritemprefab, new Vector3(0, 0, 0), Quaternion.identity);
            Transform[] allChildren = bullet3.transform.GetComponentsInChildren<Transform>();
            foreach (Transform t in allChildren)
            {
                if (t != null && t.gameObject.name == "UILabelTitle")
                    t.GetComponent<UILabel>().text = json[i]["name"];
                else if (t != null && t.gameObject.name == "UILabelInfor")
                    t.GetComponent<UILabel>().text = "Speed: " + json[i]["speed"] + "\nStrength: " + json[i]["strength"];
                else if (t != null && t.gameObject.name == "2D Sprite")
                {

                    new HTTPRequest(new Uri(json[i]["avatar"]), (request, res)
                    =>
                    {
                        var texture = new Texture2D(0, 0);
                        texture.LoadImage(res.Data);
                        t.GetComponent<UI2DSprite>().sprite2D = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    }
                    ).Send();
                }
            }
            characterList.GetComponent<UIGrid>().AddChild(bullet3.transform);
            bullet3.transform.localScale = new Vector3(1, 1, 1);
            characterList.GetComponent<UIGrid>().Reposition();
        }
    }
コード例 #16
0
	void processResponse(HTTPRequest req, HTTPResponse res) {
		Debug.Log (res.DataAsText);
		JsonReader json = new JsonReader (res.DataAsText);
		json.SkipNonMembers = true;
		NewQuestionModel response = JsonMapper.ToObject<NewQuestionModel> (json);
		Debug.Log (response.success);
		if (response.success != null) {
			MessageModel message = new MessageModel();
			if (response.success) {
				message.title = _i18n.get("MESSAGE_TITLE_OK");
				message.text = _i18n.get("MESSAGE_NEW_CHALLENGE_OK");
				message.color = Properties.colorRight;
			}
			else {
				message.title = _i18n.get("MESSAGE_TITLE_ERROR");
				message.text = _i18n.get("MESSAGE_NEW_CHALLENGE_ERROR");
				message.color = Properties.colorWrong;
			}
			_dispatcher.Dispatch("message_update", message);
		}
	}
コード例 #17
0
	void processResponse(HTTPRequest req, HTTPResponse res) {
		// send analytics
		GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus.GAProgressionStatusStart, "match");
		// enable buttons
		_dispatcher.Dispatch ("enable_new_game_button");
		// get id from response
		NewRegisterModel newGame = JsonMapper.ToObject<NewRegisterModel> (res.DataAsText);
		if (newGame.success) {
			// save game id to player pref to be retrieved later in the next scene
			PlayerPrefs.SetString ("gameId", newGame.id);
			PlayerPrefs.Save();
			// load the next scene
			_utils.loadScene ("Game");
		} 
		else {
			// if the challenged user didn't exist in the DB, inform the user
			if (newGame.errorCode == 404) {
				_dispatcher.Dispatch("error_new_game_no_exists_challenged");
				GameAnalytics.NewErrorEvent (GA_Error.GAErrorSeverity.GAErrorSeverityWarning, "Create game with non-existing user: "******"username"));
			}
		}
	}
コード例 #18
0
ファイル: PluginEvents.cs プロジェクト: Siegema/socket-test
 public AltSvcEventInfo(string host, HTTPResponse resp)
 {
     this.Host     = host;
     this.Response = resp;
 }
コード例 #19
0
        /// <summary>
        /// Checks if the given response can be cached. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
        /// </summary>
        /// <returns>Returns true if cacheable, false otherwise.</returns>
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (!IsSupported)
            {
                return(false);
            }

            if (method != HTTPMethods.Get)
            {
                return(false);
            }

            if (response == null)
            {
                return(false);
            }

            // Already cached
            if (response.StatusCode == 304)
            {
                return(false);
            }

            if (response.StatusCode < 200 || response.StatusCode >= 400)
            {
                return(false);
            }

            //http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
            var cacheControls = response.GetHeaderValues("cache-control");

            if (cacheControls != null)
            {
                if (cacheControls.Exists(headerValue => {
                    string value = headerValue.ToLower();
                    return(value.Contains("no-store") || value.Contains("no-cache"));
                }))
                {
                    return(false);
                }
            }

            var pragmas = response.GetHeaderValues("pragma");

            if (pragmas != null)
            {
                if (pragmas.Exists(headerValue => {
                    string value = headerValue.ToLower();
                    return(value.Contains("no-store") || value.Contains("no-cache"));
                }))
                {
                    return(false);
                }
            }

            // Responses with byte ranges not supported yet.
            var byteRanges = response.GetHeaderValues("content-range");

            if (byteRanges != null)
            {
                return(false);
            }

            return(true);
        }
コード例 #20
0
 private static bool IsTimeSyncResponse(HTTPResponse httpResponse)
 {
     return(httpResponse.Response.StartsWith(REQUEST_TYPE_TIMESYNC));
 }
コード例 #21
0
        /// <summary>
        /// Will parse the response, and send out the parsed packets.
        /// </summary>
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (resp != null && resp.Data != null && resp.Data.Length >= 1)
                {
                    string msg = resp.DataAsText;

                    if (msg == "ok")
                        return;
                    
                    int idx = msg.IndexOf(':', 0);
                    int startIdx = 0;

                    while (idx >= 0 && idx < msg.Length)
                    {
                        int length = int.Parse(msg.Substring(startIdx, idx - startIdx));

                        string packetData = msg.Substring(++idx, length);

                        // Binary data?
                        if (packetData.Length > 2 && packetData[0] == 'b' && packetData[1] == '4')
                        {
                            byte[] buffer = Convert.FromBase64String(packetData.Substring(2));

                            if (PacketWithAttachment != null)
                            {
                                PacketWithAttachment.AddAttachmentFromServer(buffer, true);

                                if (PacketWithAttachment.HasAllAttachment)
                                {
                                    try
                                    {
                                        OnPacket(PacketWithAttachment);
                                    }
                                    catch(Exception ex)
                                    {
                                        HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket with attachment", ex);
                                        (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                                    }
                                    finally
                                    {
                                        PacketWithAttachment = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                Packet packet = new Packet(packetData);

                                OnPacket(packet);
                            }
                            catch(Exception ex)
                            {
                                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex);
                                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                            }
                        }

                        startIdx = idx + length;
                        idx = msg.IndexOf(':', startIdx);
                    }
                }
            }
            catch (Exception ex)
            {
                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);

                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex);
            }
        }
コード例 #22
0
ファイル: UpdateTool.cs プロジェクト: dulaine/PingPongDemo
    //--------------回调方法-----------------
    #region 回调方法
    /// <summary>
    /// VersionBase下载完毕
    /// </summary>
    static void OnVersionBaseOver(HTTPRequest req, HTTPResponse resp)
    {
        Debug.Log(req.State);
        switch (req.State)
        {
        case HTTPRequestStates.Initial:
            break;

        case HTTPRequestStates.Queued:
            break;

        case HTTPRequestStates.Processing:
            break;

        case HTTPRequestStates.Finished:
            //下载完毕
            Debug.Log("versionbase.xml download complete! " + resp.DataAsText);
            //转换为xml
            StringReader reader = new StringReader(resp.DataAsText);
            XmlDocument  xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            //根节点
            XmlNode root = xmlDoc.SelectSingleNode("clientversion");
            if (root.HasChildNodes)
            {
                foreach (XmlNode item in root.ChildNodes)
                {
                    switch (item.LocalName)
                    {
                    case "versionflag":
                        mNowVersion = item.Attributes.GetNamedItem("ver").Value;
                        break;

                    case "versionres":
                        mDownloadPath = item.Attributes.Item(0).Value;              //所有文件下载地址
                        mConfNum      = 2;
                        //开始下载
                        var request = new HTTPRequest(new Uri(mDownloadPath + cPlatform), OnPlatformOver);
                        request.Send();
                        request = new HTTPRequest(new Uri(string.Concat(mDownloadPath, IOPath.Instance.NowPlatformName, "_", cVersion)), OnVersionesOver);
                        request.Send();
                        break;

                    case "loginurl":
                        //ShareSDKTool.instance.Login_Url = item.Attributes.Item(0).Value;
                        break;

                    case "payurl":
                        //ShareSDKTool.instance.Pay_Url = item.Attributes.Item(0).Value;
                        break;

                    case "authurl":
                        //ShareSDKTool.instance.Auth_Url = item.Attributes.Item(0).Value;
                        break;
                    }
                }
            }
            reader.Close();
            break;

        case HTTPRequestStates.Error:
            break;

        case HTTPRequestStates.Aborted:
            break;

        case HTTPRequestStates.ConnectionTimedOut:
            break;

        case HTTPRequestStates.TimedOut:
            break;

        default:
            break;
        }
    }
コード例 #23
0
ファイル: WebSocket.cs プロジェクト: yangxiaofei123/luarpg
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                {
                    OnError(this, req.Exception);
                }

                if (OnErrorDesc != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                    {
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;
                    }

                    OnErrorDesc(this, reason);
                }

                return;
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                {
                    OnMessage(this, msg);
                }
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                {
                    OnBinary(this, bin);
                }
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                if (OnClosed != null)
                {
                    OnClosed(this, code, msg);
                }
            };

            if (OnIncompleteFrame != null)
            {
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                    {
                        OnIncompleteFrame(this, frame);
                    }
                }
            }
            ;

            if (StartPingThread)
            {
                webSocket.StartPinging(Math.Min(PingFrequency, 100));
            }

            webSocket.StartReceive();
        }
コード例 #24
0
ファイル: expresslb.cs プロジェクト: kinifi/Express-LB
 void OnGetPlayers(HTTPRequest request, HTTPResponse response)
 {
     Debug.Log("Get: " + response.DataAsText);
 }
コード例 #25
0
        // generic internal request send
        protected Response SendRequestInternal(RequestType requestType, string url, string clientIPAddress, byte[] data, string method)
        {
            int retry = 1;

            while (true)
            {
                try
                {
                    // if beacon data is available gzip it
                    byte[] gzippedData = null;
                    if ((data != null) && (data.Length > 0))
                    {
                        gzippedData = CompressByteArray(data);

                        if (logger.IsDebugEnabled)
                        {
                            logger.Debug(GetType().Name + " Beacon Payload: " + Encoding.UTF8.GetString(data, 0, data.Length));
                        }
                    }

                    HTTPResponse httpResponse = null;
                    if (method == "GET")
                    {
                        httpResponse = GetRequest(url, clientIPAddress);
                    }
                    else if (method == "POST")
                    {
                        httpResponse = PostRequest(url, clientIPAddress, gzippedData);
                    }
                    else
                    {
                        return(UnknownErrorResponse(requestType));
                    }

                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug(GetType().Name + " HTTP Response: " + httpResponse.Response);
                        logger.Debug(GetType().Name + " HTTP Response Code: " + httpResponse.ResponseCode);
                    }

                    // create typed response based on request type and response content
                    if (requestType.RequestName == RequestType.TIMESYNC.RequestName)
                    {
                        return(httpResponse.Response == null || httpResponse.ResponseCode >= 400
                            ? new TimeSyncResponse(logger, string.Empty, httpResponse.ResponseCode, httpResponse.Headers)
                            : ParseTimeSyncResponse(httpResponse));
                    }
                    else if ((requestType.RequestName == RequestType.BEACON.RequestName) ||
                             (requestType.RequestName == RequestType.STATUS.RequestName) ||
                             (requestType.RequestName == RequestType.NEW_SESSION.RequestName))
                    {
                        return(httpResponse.Response == null || httpResponse.ResponseCode >= 400
                            ? new StatusResponse(logger, string.Empty, httpResponse.ResponseCode, httpResponse.Headers)
                            : ParseStatusResponse(httpResponse));
                    }
                    else
                    {
                        logger.Warn(GetType().Name + " Unknown request type " + requestType + " - ignoring response");
                        return(UnknownErrorResponse(requestType));
                    }
                }
                catch (Exception exception)
                {
                    retry++;
                    if (retry > MAX_SEND_RETRIES)
                    {
                        throw exception;
                    }
#if WINDOWS_UWP || NETPCL4_5
                    System.Threading.Tasks.Task.Delay(RETRY_SLEEP_TIME).Wait();
#else
                    Thread.Sleep(RETRY_SLEEP_TIME);
#endif
                }
            }
        }
コード例 #26
0
ファイル: expresslb.cs プロジェクト: kinifi/Express-LB
 private void OnUpdatePlayer(HTTPRequest request, HTTPResponse response)
 {
     Debug.Log("Put: " + response.DataAsText);
 }
コード例 #27
0
ファイル: expresslb.cs プロジェクト: kinifi/Express-LB
 private void OnCreateNewPlayer(HTTPRequest request, HTTPResponse response)
 {
     Debug.Log("Post: " + response.DataAsText);
 }
コード例 #28
0
ファイル: expresslb.cs プロジェクト: kinifi/Express-LB
 private void OnDeletePlayer(HTTPRequest request, HTTPResponse response)
 {
     Debug.Log("Delete: " + response.DataAsText);
 }
コード例 #29
0
        private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            if (this.State == ConnectionStates.CloseInitiated)
            {
                SetState(ConnectionStates.Closed);
                return;
            }

            string errorReason = null;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("HubConnection", "Negotiation Request Finished Successfully! Response: " + resp.DataAsText);

                    // Parse negotiation
                    this.NegotiationResult = NegotiationResult.Parse(resp.DataAsText, out errorReason, this);

                    // Room for improvement: check validity of the negotiation result:
                    //  If url and accessToken is present, the other two must be null.
                    //  https://github.com/aspnet/SignalR/blob/dev/specs/TransportProtocols.md#post-endpoint-basenegotiate-request

                    if (string.IsNullOrEmpty(errorReason))
                    {
                        if (this.NegotiationResult.Url != null)
                        {
                            this.SetState(ConnectionStates.Redirected);

                            if (++this.RedirectCount >= this.Options.MaxRedirects)
                            {
                                errorReason = string.Format("MaxRedirects ({0:N0}) reached!", this.Options.MaxRedirects);
                            }
                            else
                            {
                                var oldUri = this.Uri;
                                this.Uri = this.NegotiationResult.Url;

                                if (this.OnRedirected != null)
                                {
                                    try
                                    {
                                        this.OnRedirected(this, oldUri, Uri);
                                    }
                                    catch (Exception ex)
                                    {
                                        HTTPManager.Logger.Exception("HubConnection", "OnNegotiationRequestFinished - OnRedirected", ex);
                                    }
                                }

                                StartConnect();
                            }
                        }
                        else
                        {
                            ConnectImpl();
                        }
                    }
                }
                else     // Internal server error?
                {
                    errorReason = string.Format("Negotiation Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                resp.StatusCode,
                                                resp.Message,
                                                resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                errorReason = "Negotiation Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                errorReason = "Negotiation Request Aborted!";
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                errorReason = "Negotiation Request - Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                errorReason = "Negotiation Request - Processing the request Timed Out!";
                break;
            }

            if (errorReason != null)
            {
                SetState(ConnectionStates.Closed, errorReason);
            }
        }
コード例 #30
0
        private void ReadHttpStream(HTTPRequest request, HTTPResponse response)
        {
            string localfile = this.m_DownloadInfo.tempPath;

            try
            {
                List <byte[]> streamedFragments = response.GetStreamedFragments();
                if (streamedFragments != null)
                {
                    int num = 0;
                    using (FileStream fileStream = new FileStream(localfile, FileMode.Append))
                    {
                        foreach (byte[] array in streamedFragments)
                        {
                            num += array.Length;
                            fileStream.Write(array, 0, array.Length);
                        }
                    }
                    this.m_DownloadInfo.downloadedSize += num;
                    m_DownloadInfo?.OnProgressChange();
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(System.IO.IOException))
                {
                    if (Utils.IsDiskFull(ex))
                    {
                        EventManager.Instance.Trigger <SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "DiskFullException", this.m_DownloadInfo.downloadedSize).Trigger();
                    }
                    else
                    {
                        EventManager.Instance.Trigger <SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "IOException", this.m_DownloadInfo.downloadedSize).Trigger();
                    }
                }
                else
                {
                    EventManager.Instance.Trigger <SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "failure", this.m_DownloadInfo.downloadedSize).Trigger();
                }
                DebugUtil.Log("An error occured while downloading {0} due to {1}.Cancelling!", localfile, ex);
                this.m_DownloadInfo.result = DownloadResult.Failed;

                CancelDownload(true);
                this.CancelDownload(true);
                return;
            }

            float num2 = (float)this.m_DownloadInfo.downloadedSize / (float)this.m_DownloadInfo.downloadSize;

            this.m_DownloadInfo.currProgress = num2;

            //DebugUtil.Log("Downloading {0} Status: Range {1}/{2} ({3:0.00})", this.m_DownloadInfo.fileName, this.m_DownloadInfo.downloadedSize, this.m_DownloadInfo.downloadSize, this.m_DownloadInfo.currProgress);
            if (!response.IsStreamingFinished || request.State != HTTPRequestStates.Finished)
            {
                return;
            }

            DebugUtil.Log("Download finished : {0}", this.m_DownloadInfo.savePath);
            this.m_DownloadInfo.currProgress = 1.0f;

            // 续传完成后,做一手MD5验证
            string localMd5 = AssetUtils.BuildFileMd5(localfile);

            if (localMd5.Trim() != m_DownloadInfo.fileMd5.Trim())
            {
                //md5验证失败,删除临时文件
                if (File.Exists(localfile))
                {
                    File.Delete(localfile);
                }

                DebugUtil.Log("md5 error, retry download:" + localfile + " =>" + localMd5 + " ## " + m_DownloadInfo.fileMd5);
                this.m_DownloadInfo.result       = DownloadResult.Md5Error;
                this.m_DownloadInfo.currProgress = 0.0f;
                CancelDownload(true);
            }
            else
            {// md5验证通过,临时文件转为最终文件
                string localfile2 = m_DownloadInfo.savePath;
                if (File.Exists(localfile2))
                {
                    File.Delete(localfile2);
                }

                DebugUtil.Log("md5 check success, move temp to final :" + this.m_DownloadInfo.fileName);
                File.Move(localfile, localfile2);
                this.m_DownloadInfo.result = DownloadResult.Success;
                DownloadManager.Instance.FinishDownloadTask(this.m_DownloadInfo);
            }

            EventManager.Instance.Trigger <SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "finish", m_DownloadInfo.downloadedSize).Trigger();
        }
コード例 #31
0
        void OnConnectRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            // error reason if there is any. We will call the manager's Error function if it's not empty.
            string reason = string.Empty;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("Transport - " + this.Name, "Connect - Request Finished Successfully! " + resp.DataAsText);

                    OnConnected();

                    IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);

                    if (msg != null)
                    {
                        Connection.OnMessage(msg);

                        MultiMessage multiple = msg as MultiMessage;
                        if (multiple != null && multiple.PollDelay.HasValue)
                        {
                            PollDelay = multiple.PollDelay.Value;
                        }
                    }
                }
                else
                {
                    reason = string.Format("Connect - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           resp.StatusCode,
                                           resp.Message,
                                           resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                reason = "Connect - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                reason = "Connect - Request Aborted!";
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                reason = "Connect - Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                reason = "Connect - Processing the request Timed Out!";
                break;
            }

            if (!string.IsNullOrEmpty(reason))
            {
                Connection.Error(reason);
            }
        }
コード例 #32
0
ファイル: WebSocket.cs プロジェクト: yangxiaofei123/luarpg
        private void OnInternalRequestCallback(HTTPRequest req, HTTPResponse resp)
        {
            string reason = string.Empty;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess || resp.StatusCode == 101)
                {
                    HTTPManager.Logger.Information("WebSocket", string.Format("Request finished. Status Code: {0} Message: {1}", resp.StatusCode.ToString(), resp.Message));

                    return;
                }
                else
                {
                    reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           resp.StatusCode,
                                           resp.Message,
                                           resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                reason = "Request Finished with Error! " + (req.Exception != null ? ("Exception: " + req.Exception.Message + req.Exception.StackTrace) : string.Empty);
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                reason = "Request Aborted!";
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                reason = "Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                reason = "Processing the request Timed Out!";
                break;

            default:
                return;
            }

            if (OnError != null)
            {
                OnError(this, req.Exception);
            }

            if (OnErrorDesc != null)
            {
                OnErrorDesc(this, reason);
            }

            if (OnError == null && OnErrorDesc == null)
            {
                HTTPManager.Logger.Error("WebSocket", reason);
            }
        }
コード例 #33
0
        void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            // When Stop() called on the transport.
            // In Stop() we set the pollRequest to null, but a new poll request can be made after a quick reconnection, and there is a chanse that
            // in this handler function we can null out the new request. So we return early here.
            if (req.State == HTTPRequestStates.Aborted)
            {
                HTTPManager.Logger.Warning("Transport - " + this.Name, "Poll - Request Aborted!");
                return;
            }

            // Set the pollRequest to null, now we can send out a new one
            pollRequest = null;

            // error reason if there is any. We will call the manager's Error function if it's not empty.
            string reason = string.Empty;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("Transport - " + this.Name, "Poll - Request Finished Successfully! " + resp.DataAsText);

                    IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);

                    if (msg != null)
                    {
                        Connection.OnMessage(msg);

                        MultiMessage multiple = msg as MultiMessage;
                        if (multiple != null && multiple.PollDelay.HasValue)
                        {
                            PollDelay = multiple.PollDelay.Value;
                        }

                        LastPoll = DateTime.UtcNow;
                    }
                }
                else
                {
                    reason = string.Format("Poll - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           resp.StatusCode,
                                           resp.Message,
                                           resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                reason = "Poll - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                reason = "Poll - Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                reason = "Poll - Processing the request Timed Out!";
                break;
            }

            if (!string.IsNullOrEmpty(reason))
            {
                Connection.Error(reason);
            }
        }
コード例 #34
0
        private object RouteSendRawTx(HTTPRequest request)
        {
            if (!HasLogin(request))
            {
                return(HTTPResponse.Redirect("/login"));
            }

            var isFungible = bool.Parse(request.GetVariable("fungible"));
            var addressTo  = request.GetVariable("dest");

            var chainName        = request.GetVariable("chain");
            var destinationChain = request.GetVariable("destChain");

            var symbol     = request.GetVariable("token");
            var amountOrId = request.GetVariable(isFungible ? "amount" : "id");

            var    keyPair = GetLoginKey(request);
            string result;

            if (chainName == destinationChain)
            {
                result = AccountController.TransferTokens(isFungible, keyPair, addressTo, chainName, symbol, amountOrId).Result;

                ResetSessionSendFields(request);
            }
            else //cross chain requires 2 txs
            {
                var pathList = AccountController.GetShortestPath(chainName, destinationChain).ToArray();

                request.session.SetInt("txNumber", pathList.Length);

                if (pathList.Length > 2)
                {
                    chainName        = pathList[0].Name;
                    destinationChain = pathList[1].Name;

                    // save tx
                    request.session.SetStruct <TransferTx>("transferTx", new TransferTx
                    {
                        IsFungible = isFungible,
                        FromChain  = chainName,
                        ToChain    = destinationChain,
                        FinalChain = pathList[pathList.Length - 1].Name,
                        AddressTo  = addressTo,
                        Symbol     = symbol,
                        AmountOrId = amountOrId
                    });

                    result = AccountController.CrossChainTransferToken(isFungible, keyPair, keyPair.Address.Text, chainName, destinationChain, symbol, amountOrId).Result;
                }
                else
                {
                    result = AccountController.CrossChainTransferToken(isFungible, keyPair, addressTo, chainName, destinationChain, symbol, amountOrId).Result;
                }
                if (SendUtils.IsTxHashValid(result))
                {
                    request.session.SetBool("isCrossTransfer", true);
                    request.session.SetStruct <SettleTx>("settleTx",
                                                         new SettleTx
                    {
                        ChainName               = chainName,
                        ChainAddress            = AccountController.PhantasmaChains.Find(p => p.Name == chainName).Address,
                        DestinationChainAddress = AccountController.PhantasmaChains.Find(p => p.Name == destinationChain).Address,
                    });
                }
            }

            if (!SendUtils.IsTxHashValid(result))
            {
                PushError(request, result);
                return("");
            }

            return(result);
        }
コード例 #35
0
 public void OnAfterHttpResponseEventHandler(IHTTPClient source, HTTPResponse response)
 {
     Response = response;
 }
コード例 #36
0
ファイル: EventSource.cs プロジェクト: ubberkid/PeerATT
        private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            if (this.State == States.Closed)
                return;

            if (this.State == States.Closing)
            {
                SetClosed("OnRequestFinished");

                return;
            }

            string reason = string.Empty;

            // In some cases retry is prohibited
            bool canRetry = true;

            switch (req.State)
            {
                // The server sent all the data it's wanted.
                case HTTPRequestStates.Processing:
                    canRetry = !resp.HasHeader("content-length");
                    break;

                // The request finished without any problem.
                case HTTPRequestStates.Finished:
                    // HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or that have no Content-Type at all, must cause the user agent to fail the connection.
                    if (resp.StatusCode == 200 && !resp.HasHeaderWithValue("content-type", "text/event-stream"))
                    {
                        reason = "No Content-Type header with value 'text/event-stream' present.";
                        canRetry = false;
                    }

                    // HTTP 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout responses, and any network error that prevents the connection 
                    //  from being established in the first place (e.g. DNS errors), must cause the user agent to asynchronously reestablish the connection.
                    // Any other HTTP response code not listed here must cause the user agent to fail the connection.
                    if (canRetry &&
                        resp.StatusCode != 500 &&
                        resp.StatusCode != 502 &&
                        resp.StatusCode != 503 &&
                        resp.StatusCode != 504)
                    {
                        canRetry = false;

                        reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                        resp.StatusCode,
                                                        resp.Message,
                                                        resp.DataAsText);
                    }
                    break;

                // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
                case HTTPRequestStates.Error:
                    reason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                    break;

                // The request aborted, initiated by the user.
                case HTTPRequestStates.Aborted:
                    // If the state is Closing, then it's a normal behaviour, and we close the EventSource
                    reason = "OnRequestFinished - Aborted without request. EventSource's State: " + this.State;
                    break;

                // Ceonnecting to the server is timed out.
                case HTTPRequestStates.ConnectionTimedOut:
                    reason = "Connection Timed Out!";
                    break;

                // The request didn't finished in the given time.
                case HTTPRequestStates.TimedOut:
                    reason = "Processing the request Timed Out!";
                    break;
            }

            // If we are not closing the EventSource, then we will try to reconnect.
            if (this.State < States.Closing)
            {
                if (!string.IsNullOrEmpty(reason))
                    CallOnError(reason, "OnRequestFinished");

                if (canRetry)
                    Retry();
                else
                    SetClosed("OnRequestFinished");
            }
            else
                SetClosed("OnRequestFinished");
        }
コード例 #37
0
ファイル: API.cs プロジェクト: wwwK/ME_NLua
    static IEnumerator onDownLoadCompleted(LuaFunction completeHander, object complete_param, HTTPRequest req, HTTPResponse resp)
    {
        yield return(new WaitForEndOfFrame());

        if (complete_param != null)
        {
            completeHander.Call(req, resp, complete_param);
        }
        else
        {
            completeHander.Call(req, resp);
        }
    }
コード例 #38
0
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                    OnError(this, req.Exception);

                if (OnErrorDesc != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;

                    OnErrorDesc(this, reason);
                }

                return;
            }

            webSocket.WebSocket = this;

            if (this.Extensions != null)
            {
                for (int i = 0; i < this.Extensions.Length; ++i)
                {
                    var ext = this.Extensions[i];

                    try
                    {
                        if (ext != null && !ext.ParseNegotiation(webSocket))
                            this.Extensions[i] = null; // Keep extensions only that succesfully negotiated
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("WebSocket", "ParseNegotiation", ex);

                        // Do not try to use a defective extension in the future
                        this.Extensions[i] = null;
                    }
                }
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch(Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                    OnMessage(this, msg);
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                    OnBinary(this, bin);
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                if (OnClosed != null)
                    OnClosed(this, code, msg);
            };

            if (OnIncompleteFrame != null)
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                        OnIncompleteFrame(this, frame);
                };

            if (StartPingThread)
                webSocket.StartPinging(Math.Max(PingFrequency, 100));

            webSocket.StartReceive();
        }
コード例 #39
0
 public Response(ResponseBody error, HTTPResponse httpResponse)
 {
     ErrorBody    = error;
     HttpResponse = httpResponse;
 }
コード例 #40
0
 private static bool IsStatusResponse(HTTPResponse httpResponse)
 {
     return(httpResponse.Response.StartsWith(REQUEST_TYPE_MOBILE));
 }
コード例 #41
0
ファイル: EventSource.cs プロジェクト: ubberkid/PeerATT
        /// <summary>
        /// We are successfully upgraded to the EventSource protocol, we can start to receive and parse the incoming data.
        /// </summary>
        private void OnUpgraded(HTTPRequest originalRequest, HTTPResponse response)
        {
            EventSourceResponse esResponse = response as EventSourceResponse;

            if (esResponse == null)
            {
                CallOnError("Not an EventSourceResponse!", "OnUpgraded");
                return;
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
                }
            }

            esResponse.OnMessage += OnMessageReceived;
            esResponse.StartReceive();

            this.RetryCount = 0;
            this.State = States.Open;
        }
コード例 #42
0
 public Response(T data, HTTPResponse httpResponse)
 {
     Data         = data;
     HttpResponse = httpResponse;
 }
コード例 #43
0
        private void OnInternalRequestCallback(HTTPRequest req, HTTPResponse resp)
        {
            string reason = string.Empty;

            switch (req.State)
            {
                // The request finished without any problem.
                case HTTPRequestStates.Finished:
                    if (resp.IsSuccess || resp.StatusCode == 101)
                    {
                        HTTPManager.Logger.Information("WebSocket", string.Format("Request finished. Status Code: {0} Message: {1}", resp.StatusCode.ToString(), resp.Message));

                        return;
                    }
                    else
                        reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                        resp.StatusCode,
                                                        resp.Message,
                                                        resp.DataAsText);
                    break;

                // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
                case HTTPRequestStates.Error:
                    reason = "Request Finished with Error! " + (req.Exception != null ? ("Exception: " + req.Exception.Message + req.Exception.StackTrace) : string.Empty);
                    break;

                // The request aborted, initiated by the user.
                case HTTPRequestStates.Aborted:
                    reason = "Request Aborted!";
                    break;

                // Ceonnecting to the server is timed out.
                case HTTPRequestStates.ConnectionTimedOut:
                    reason = "Connection Timed Out!";
                    break;

                // The request didn't finished in the given time.
                case HTTPRequestStates.TimedOut:
                    reason = "Processing the request Timed Out!";
                    break;

                default:
                    return;
            }

            if (OnError != null)
                OnError(this, req.Exception);

            if (OnErrorDesc != null)
                OnErrorDesc(this, reason);

            if (OnError == null && OnErrorDesc == null)
                HTTPManager.Logger.Error("WebSocket", reason);
        }
コード例 #44
0
ファイル: ConfigManager.cs プロジェクト: Keyj1n/BattlePong
    private Dictionary<string, object> ParseResponse(HTTPResponse response) {
			// TODO fix exception ArgumentNullException: Argument cannot be null. when connection is down 
			if (response == null) return null;
      string jsonString = System.Text.Encoding.UTF8.GetString(response.data, 0, response.dataLength);
      object jsonObject = MiniJSON.Json.Deserialize(jsonString);
      if(jsonObject != null && jsonObject is Dictionary<string, object>) {
        Dictionary<string, object> json = (Dictionary<string, object>)jsonObject;
        long statusCode = (long)json["status"];
        if(statusCode != 200) {
          string errorMessage = (string)json["error"];
          throw new Exception(errorMessage);
        }
        Dictionary<string, object> data = (Dictionary<string, object>)json["data"];
        return data;
      }
      return null;
    }
コード例 #45
0
        private void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            // Clear the PollRequest variable, so we can start a new poll.
            PollRequest = null;

            if (State == TransportStates.Closed)
                return;

            string errorString = null;

            switch (req.State)
            {
                // The request finished without any problem.
                case HTTPRequestStates.Finished:

                    if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
                        HTTPManager.Logger.Verbose("PollingTransport", "OnPollRequestFinished: " + resp.DataAsText);

                    if (resp.IsSuccess)
                        ParseResponse(resp);
                    else
                        errorString = string.Format("Polling - Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
                                                            resp.StatusCode,
                                                            resp.Message,
                                                            resp.DataAsText,
                                                            req.CurrentUri);
                    break;

                // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
                case HTTPRequestStates.Error:
                    errorString = req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception";
                    break;

                // The request aborted, initiated by the user.
                case HTTPRequestStates.Aborted:
                    errorString = string.Format("Polling - Request({0}) Aborted!", req.CurrentUri);
                    break;

                // Ceonnecting to the server is timed out.
                case HTTPRequestStates.ConnectionTimedOut:
                    errorString = string.Format("Polling - Connection Timed Out! Uri: {0}", req.CurrentUri);
                    break;

                // The request didn't finished in the given time.
                case HTTPRequestStates.TimedOut:
                    errorString = string.Format("Polling - Processing the request({0}) Timed Out!", req.CurrentUri);
                    break;
            }

            if (!string.IsNullOrEmpty(errorString))
                (Manager as IManager).OnTransportError(this, errorString);
        }
コード例 #46
0
 private HTTPResponse RouteLogout(HTTPRequest request)
 {
     request.session.Remove("login");
     return(HTTPResponse.Redirect("/login"));
 }
コード例 #47
0
ファイル: UserSave.cs プロジェクト: wmy-wmy/Unity3d-model
    void OnRequestFinished(HTTPRequest request, HTTPResponse response)
    {
//       Debug.Log("Request Finished! Text received: " + response.DataAsText);
    }
コード例 #48
0
        protected virtual void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    DateTime downloadStarted = (DateTime)req.Tag;
                    TimeSpan diff            = DateTime.Now - downloadStarted;

                    this._statusText.text = string.Format("Streaming finished in {0:N0}ms", diff.TotalMilliseconds);
                }
                else
                {
                    this._statusText.text = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                          resp.StatusCode,
                                                          resp.Message,
                                                          resp.DataAsText);
                    Debug.LogWarning(this._statusText.text);

                    request = null;
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                this._statusText.text = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                Debug.LogError(this._statusText.text);

                request = null;
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                this._statusText.text = "Request Aborted!";
                Debug.LogWarning(this._statusText.text);

                request = null;
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                this._statusText.text = "Connection Timed Out!";
                Debug.LogError(this._statusText.text);

                request = null;
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                this._statusText.text = "Processing the request Timed Out!";
                Debug.LogError(this._statusText.text);

                request = null;
                break;
            }

            // UI

            this._streamingSetupRoot.gameObject.SetActive(true);
            this._reportingRoot.gameObject.SetActive(false);

            this._startDownload.interactable  = true;
            this._cancelDownload.interactable = false;
            request = null;
        }
コード例 #49
0
        /// <summary>
        /// Private event handler that called when the handshake request finishes.
        /// </summary>
        private void OnHandshakeCallback(HTTPRequest req, HTTPResponse resp)
        {
            HandshakeRequest = null;

            switch (req.State)
            {
                case HTTPRequestStates.Finished:
                    if (resp.IsSuccess)
                    {
                        HTTPManager.Logger.Information("HandshakeData", "Handshake data arrived: " + resp.DataAsText);

                        int idx = resp.DataAsText.IndexOf("{");
                        if (idx < 0)
                        {
                            RaiseOnError("Invalid handshake text: " + resp.DataAsText);
                            return;
                        }

                        var Handshake = Parse(resp.DataAsText.Substring(idx));

                        if (Handshake == null)
                        {
                            RaiseOnError("Parsing Handshake data failed: " + resp.DataAsText);
                            return;
                        }

                        if (OnReceived != null)
                        {
                            OnReceived(this);
                            OnReceived = null;
                        }
                    }
                    else
                        RaiseOnError(string.Format("Handshake request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
                                                                    resp.StatusCode,
                                                                    resp.Message,
                                                                    resp.DataAsText,
                                                                    req.CurrentUri));
                    break;

                case HTTPRequestStates.Error:
                    RaiseOnError(req.Exception != null ? (req.Exception.Message + " " + req.Exception.StackTrace) : string.Empty);
                    break;

                default:
                    RaiseOnError(req.State.ToString());
                    break;
            }
        }
コード例 #50
0
            public static bool TwitchWhoIsLiveManager_onGameLiveStreamRequestFinished_Prefix(HTTPResponse response, ref List <TwitchStreamInfo> ____streamInfos, ref bool ____hasEverRetirevedLiveUsers)
            {
                if (response == null || !response.IsSuccess)
                {
                    return(false);
                }

                try
                {
                    ____streamInfos = new List <TwitchStreamInfo>();

                    foreach (JToken jtoken in JsonConvert.DeserializeObject <JContainer>(response.DataAsText).First.First.Children())
                    {
                        TwitchStreamInfo twitchStreamInfo = jtoken.ToObject <TwitchStreamInfo>();
                        ____streamInfos.Add(twitchStreamInfo);
                    }

                    ____hasEverRetirevedLiveUsers = true;

                    GlobalEventManager.Instance.Dispatch(GlobalEvents.TwitchLiveStreamsRefreshed);
                }
                catch (Exception exception)
                {
                    ErrorManager.Instance.LogExceptionWithoutPausingGame(exception, "onGameLiveStreamRequestFinished Error");
                }

                return(false);
            }
コード例 #51
0
 protected abstract void OnDidReceiveData(HTTPResponse response,
     byte[] buffer, ulong length);
コード例 #52
0
        /// <summary>
        /// Checks if the given response can be cached. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
        /// </summary>
        /// <returns>Returns true if cacheable, false otherwise.</returns>
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (!IsSupported)
            {
                return(false);
            }

            if (method != HTTPMethods.Get)
            {
                return(false);
            }

            if (response == null)
            {
                return(false);
            }

            // https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.12 - Cache Replacement
            // It MAY insert it into cache storage and MAY, if it meets all other requirements, use it to respond to any future requests that would previously have caused the old response to be returned.
            //if (response.StatusCode == 304)
            //    return false;

            // Partial response
            if (response.StatusCode == 206)
            {
                return(false);
            }

            if (response.StatusCode < 200 || response.StatusCode >= 400)
            {
                return(false);
            }

            //http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
            var cacheControls = response.GetHeaderValues("cache-control");

            if (cacheControls != null)
            {
                if (cacheControls.Exists(headerValue =>
                {
                    string value = headerValue.ToLower();
                    if (value.StartsWith("max-age"))
                    {
                        string[] kvp = headerValue.FindOption("max-age");
                        if (kvp != null)
                        {
                            // Some cache proxies will return float values
                            double maxAge;
                            if (double.TryParse(kvp[1], out maxAge))
                            {
                                // A negative max-age value is a no cache
                                if (maxAge <= 0)
                                {
                                    return(false);
                                }
                            }
                        }
                    }

                    // https://csswizardry.com/2019/03/cache-control-for-civilians/#no-store
                    return(value.Contains("no-store"));
                }))
                {
                    return(false);
                }
            }

            var pragmas = response.GetHeaderValues("pragma");

            if (pragmas != null)
            {
                if (pragmas.Exists(headerValue =>
                {
                    string value = headerValue.ToLower();
                    return(value.Contains("no-store") || value.Contains("no-cache"));
                }))
                {
                    return(false);
                }
            }

            // Responses with byte ranges not supported yet.
            var byteRanges = response.GetHeaderValues("content-range");

            if (byteRanges != null)
            {
                return(false);
            }

            // Store only if at least one caching header with proper value present

            var etag = response.GetFirstHeaderValue("ETag");

            if (!string.IsNullOrEmpty(etag))
            {
                return(true);
            }

            var expires = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0));

            if (expires >= DateTime.UtcNow)
            {
                return(true);
            }

            if (response.GetFirstHeaderValue("Last-Modified") != null)
            {
                return(true);
            }

            return(false);
        }
コード例 #53
0
ファイル: ConfigManager.cs プロジェクト: Keyj1n/BattlePong
    private void HandleAdSourcesResponse(HTTPResponse response) {
      Dictionary<string, object> data;
      try {
        data = ParseResponse(response);
      }
      catch(Exception) {
        return;
      }

      if(data == null) {
        return;
      }

      Utils.LogDebug("Received ad sources response");

      globalIntervals = new IntervalManager((List<object>)data["adIntervals"]);

      Utils.LogDebug("Got " + globalIntervals + " intervals for global");

      serverTimestamp = (long)data["serverTimestamp"];
      localTimestamp = (long)Math.Round(Time.realtimeSinceStartup);

      ZoneManager.Instance.UpdateIntervals((Dictionary<string, object>)data["adSources"]);

      _requestingAdSources = false;
    }
コード例 #54
0
        internal static System.IO.Stream PrepareStreamed(Uri uri, HTTPResponse response)
        {
            HTTPCacheFileInfo info;

            lock (Library)
            {
                if (!Library.TryGetValue(uri, out info))
                    Library.Add(uri, info = new HTTPCacheFileInfo(uri));

                try
                {
                    return info.GetSaveStream(response);
                }
                catch
                {
                    // If something happens while we write out the response, than we will delete it becouse it might be in an invalid state.
                    DeleteEntity(uri);

                    throw;
                }
            }
        }
コード例 #55
0
        private void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            // Clear the PollRequest variable, so we can start a new poll.
            PollRequest = null;

            if (State == TransportStates.Closed)
            {
                return;
            }

            string errorString = null;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:

                if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
                {
                    HTTPManager.Logger.Verbose("PollingTransport", "OnPollRequestFinished: " + resp.DataAsText, this.Manager.Context);
                }

                if (resp.IsSuccess)
                {
                    ParseResponse(resp);
                }
                else
                {
                    errorString = string.Format("Polling - Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
                                                resp.StatusCode,
                                                resp.Message,
                                                resp.DataAsText,
                                                req.CurrentUri);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                errorString = req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception";
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                errorString = string.Format("Polling - Request({0}) Aborted!", req.CurrentUri);
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                errorString = string.Format("Polling - Connection Timed Out! Uri: {0}", req.CurrentUri);
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                errorString = string.Format("Polling - Processing the request({0}) Timed Out!", req.CurrentUri);
                break;
            }

            if (!string.IsNullOrEmpty(errorString))
            {
                (Manager as IManager).OnTransportError(this, errorString);
            }
        }
コード例 #56
0
 private HTTPResponse RouteHome(HTTPRequest request)
 {
     return(HTTPResponse.Redirect(HasLogin(request) ? "/portfolio" : "/login"));
 }
コード例 #57
0
        /// <summary>
        /// Checks if the given response can be cached. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
        /// </summary>
        /// <returns>Returns true if cacheable, false otherwise.</returns>
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (method != HTTPMethods.Get)
                return false;

            if (response == null)
                return false;

            // Already cached
            if (response.StatusCode == 304)
                return false;

            if (response.StatusCode < 200 || response.StatusCode >= 400)
                return false;

            //http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
            var cacheControls = response.GetHeaderValues("cache-control");
            if (cacheControls != null && cacheControls[0].ToLower().Contains("no-store"))
                return false;

            var pragmas = response.GetHeaderValues("pragma");
            if (pragmas != null && pragmas[0].ToLower().Contains("no-cache"))
                return false;

            // Responses with byte ranges not supported yet.
            var byteRanges = response.GetHeaderValues("content-range");
            if (byteRanges != null)
                return false;

            return true;
        }
コード例 #58
0
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (resp == null || resp.Data == null || resp.Data.Length < 1)
                {
                    return;
                }

                int idx = 0;
                while (idx < resp.Data.Length)
                {
                    int endIdx = FindNextRecordSeparator(resp.Data, idx);
                    int length = endIdx - idx;

                    if (length <= 0)
                    {
                        break;
                    }

                    IncomingPacket packet = IncomingPacket.Empty;

                    if (resp.Data[idx] == 'b')
                    {
                        // First byte is the binary indicator('b'). We must skip it, so we advance our idx and also have to decrease length
                        idx++;
                        length--;
                        var base64Encoded = System.Text.Encoding.UTF8.GetString(resp.Data, idx, length);
                        var byteData      = Convert.FromBase64String(base64Encoded);
                        packet = this.Manager.Parser.Parse(this.Manager, new BufferSegment(byteData, 0, byteData.Length));
                    }
                    else
                    {
                        // It's the handshake data?
                        if (this.State == TransportStates.Opening)
                        {
                            TransportEventTypes transportEvent = (TransportEventTypes)(resp.Data[idx] - '0');
                            if (transportEvent == TransportEventTypes.Open)
                            {
                                var handshake = BestHTTP.JSON.LitJson.JsonMapper.ToObject <HandshakeData>(Encoding.UTF8.GetString(resp.Data, idx + 1, length - 1));
                                packet            = new IncomingPacket(TransportEventTypes.Open, SocketIOEventTypes.Unknown, "/", -1);
                                packet.DecodedArg = handshake;
                            }
                            else
                            {
                                // TODO: error?
                            }
                        }
                        else
                        {
                            packet = this.Manager.Parser.Parse(this.Manager, System.Text.Encoding.UTF8.GetString(resp.Data, idx, length));
                        }
                    }

                    if (!packet.Equals(IncomingPacket.Empty))
                    {
                        try
                        {
                            OnPacket(packet);
                        }
                        catch (Exception ex)
                        {
                            HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex, this.Manager.Context);
                            (Manager as IManager).EmitError(ex.Message + " " + ex.StackTrace);
                        }
                    }

                    idx = endIdx + 1;
                }
            }
            catch (Exception ex)
            {
                (Manager as IManager).EmitError(ex.Message + " " + ex.StackTrace);

                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex, this.Manager.Context);
            }
        }
コード例 #59
0
        internal static HTTPCacheFileInfo Store(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (response == null || response.Data == null || response.Data.Length == 0)
                return null;

            HTTPCacheFileInfo info = null;

            lock (Library)
            {
                if (!Library.TryGetValue(uri, out info))
                    Library.Add(uri, info = new HTTPCacheFileInfo(uri));

                try
                {
                    info.Store(response);
                }
                catch
                {
                    // If something happens while we write out the response, than we will delete it becouse it might be in an invalid state.
                    DeleteEntity(uri);

                    throw;
                }
            }

            return info;
        }
コード例 #60
0
    void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
    {
        switch (req.State)
        {
        // The request finished without any problem.
        case HTTPRequestStates.Finished:
            Debug.Log("Request Finished! Text received: " + resp.DataAsText);
            if (resp.DataAsText.Contains("ENOENT"))
            {
                MeditorManager.Instance.MeditorUi.SetAccess("Url Error.");
                return;
            }
            SetReceiveConfigFlag(true);
            ConfigConfigDic(resp);
            if (ConfigDictionary.TryGetValue("access", out accessStr))
            {
                //加载成功
                if (accessStr == "true")
                {
                    MeditorManager.Instance.MeditorUi.SetDownLoadReady();
                }
                else
                {
                    MeditorManager.Instance.MeditorUi.SetAccess("access denied.");
                }
            }
            else
            {
                MeditorManager.Instance.MeditorUi.SetAccess("Not such a key \"access\"");
            }
            Debug.Log("Request Finished Successfully!\n" + resp.DataAsText);
            break;


        // The request finished with an unexpected error.
        // The request's Exception property may contain more information about the error.
        case HTTPRequestStates.Error:
            string errinfo = "Request Finished with Error! " +
                             (req.Exception != null
                                     ? (req.Exception.Message + "\n" + req.Exception.StackTrace)
                                     : "No Exception");
            MeditorManager.Instance.MeditorUi.SetAccess(errinfo);
            Debug.LogError(errinfo);
            break;


        // The request aborted, initiated by the user.
        case HTTPRequestStates.Aborted:
            MeditorManager.Instance.MeditorUi.SetAccess("Request Aborted!");
            Debug.LogWarning("Request Aborted!");
            break;


        // Ceonnecting to the server timed out.
        case HTTPRequestStates.ConnectionTimedOut:
            MeditorManager.Instance.MeditorUi.SetAccess("Connection Timed Out!");
            Debug.LogError("Connection Timed Out!");
            break;

        // The request didn't finished in the given time.
        case HTTPRequestStates.TimedOut:
            Debug.LogError("Processing the request Timed Out!");
            break;
        }
    }