コード例 #1
0
 internal HttpListenerResponse() {
     if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "");
     m_NativeResponse = new UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE();
     m_WebHeaders = new WebHeaderCollection(WebHeaderCollectionType.HttpListenerResponse);
     m_BoundaryType = BoundaryType.None;
     m_NativeResponse.StatusCode = (ushort)HttpStatusCode.OK;
     m_NativeResponse.Version.MajorVersion = 1;
     m_NativeResponse.Version.MinorVersion = 1;
     m_KeepAlive = true;
     m_ResponseState = ResponseState.Created;
 }
コード例 #2
0
ファイル: ShareButton.cs プロジェクト: AhrenLi/2048
 void ShareResultHandler(ResponseState state, PlatformType type, Hashtable shareInfo, Hashtable error, bool end)
 {
     if (state == ResponseState.Success) {
         print("share result :");
         print(MiniJSON.jsonEncode(shareInfo));
     } else if (state == ResponseState.Fail) {
         print("fail! error code = " + error["error_code"] + "; error msg = " + error["error_msg"]);
     } else if (state == ResponseState.Cancel) {
         print("cancel !");
     }
 }
コード例 #3
0
 internal HttpListenerResponse()
 {
     if (NetEventSource.IsEnabled) NetEventSource.Info(this);
     _nativeResponse = new Interop.HttpApi.HTTP_RESPONSE();
     _webHeaders = new WebHeaderCollection();
     _boundaryType = BoundaryType.None;
     _nativeResponse.StatusCode = (ushort)HttpStatusCode.OK;
     _nativeResponse.Version.MajorVersion = 1;
     _nativeResponse.Version.MinorVersion = 1;
     _keepAlive = true;
     _responseState = ResponseState.Created;
 }
コード例 #4
0
ファイル: Demo.cs プロジェクト: andyAHG/Unity3DShareSDKSample
 void AuthResultHandler(ResponseState state, PlatformType type, Hashtable error)
 {
     if (state == ResponseState.Success)
     {
         print ("success !");
     }
     else if (state == ResponseState.Fail)
     {
         print ("fail! error code = " + error["error_code"] + "; error msg = " + error["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         print ("cancel !");
     }
 }
コード例 #5
0
 void AuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
 {
     if (state == ResponseState.Success)
     {
         print ("authorize success !");
     }
     else if (state == ResponseState.Fail)
     {
         print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         print ("cancel !");
     }
 }
コード例 #6
0
 void FollowFriendResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
 {
     if (state == ResponseState.Success)
     {
         print ("Follow friend successfully !");
     }
     else if (state == ResponseState.Fail)
     {
         print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         print ("cancel !");
     }
 }
コード例 #7
0
 void GetUserInfoResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
 {
     if (state == ResponseState.Success)
     {
         print ("get user info result :");
         print (MiniJSON.jsonEncode(result));
     }
     else if (state == ResponseState.Fail)
     {
         print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         print ("cancel !");
     }
 }
コード例 #8
0
ファイル: Demo.cs プロジェクト: andyAHG/Unity3DShareSDKSample
 void GetFriendsResultHandler(ResponseState state, PlatformType type, ArrayList friends, Hashtable error)
 {
     if (state == ResponseState.Success)
     {
         print ("share result :");
         print (MiniJSON.jsonEncode(friends));
     }
     else if (state == ResponseState.Fail)
     {
         print ("fail! error code = " + error["error_code"] + "; error msg = " + error["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         print ("cancel !");
     }
 }
コード例 #9
0
ファイル: Demo.cs プロジェクト: andyAHG/Unity3DShareSDKSample
 void GetTokenResultHandler(ResponseState state, PlatformType type, Hashtable credential, Hashtable error)
 {
     if (state == ResponseState.Success)
     {
         print ("share result :");
         print (MiniJSON.jsonEncode(credential));
     }
     else if (state == ResponseState.Fail)
     {
         print ("fail! error code = " + error["error_code"] + "; error msg = " + error["error_msg"]);
     }
     else if (state == ResponseState.Cancel)
     {
         print ("cancel !");
     }
 }
コード例 #10
0
 /// <summary>
 /// 获取用户基本信息(包括UnionID机制)
 /// </summary>
 /// <param name="access_Token">微信号access_Token</param>
 /// <param name="openID">用户openID</param>
 /// <param name="lang">语言</param>
 /// <param name="state">状态</param>
 /// <returns></returns>
 public static UserDetail GetUserDetail(string access_Token, string openID, out ResponseState state)
 {
     return(GetUserDetail(access_Token, openID, Lang.Zh_CN, out state));
 }
コード例 #11
0
ファイル: SocketBase.cs プロジェクト: mmarzz/AutoCSer
 /// <summary>
 /// 输出错误状态
 /// </summary>
 /// <param name="identity">操作标识</param>
 /// <param name="state">错误状态</param>
 /// <returns>是否匹配会话标识</returns>
 public abstract bool ResponseError(long identity, ResponseState state);
コード例 #12
0
        /*
         * 12.3
         * HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
         * The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:
         *
         #define HTTP_SEND_RESPONSE_FLAG_DISCONNECT          0x00000001
         #define HTTP_SEND_RESPONSE_FLAG_MORE_DATA           0x00000002
         #define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER          0x00000004
         #define HTTP_SEND_RESPONSE_FLAG_VALID               0x00000007
         *
         * HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
         *  specifies that the network connection should be disconnected immediately after
         *  sending the response, overriding the HTTP protocol's persistent connection features.
         * HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
         *  specifies that additional entity body data will be sent by the caller. Thus,
         *  the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
         * HTTP_SEND_RESPONSE_RAW_HEADER:
         *  specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
         *  a call to HttpSendHttpResponse() in order to bypass normal header processing. The
         *  actual HTTP header will be generated by the application and sent as entity body.
         *  This flag should be passed on the first call to HttpSendResponseEntityBody, and
         *  not after. Thus, flag is not applicable to HttpSendHttpResponse.
         */
        internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK *pDataChunk,
                                         HttpResponseStreamAsyncResult asyncResult,
                                         Interop.HttpApi.HTTP_FLAGS flags,
                                         bool isWebSocketHandshake)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"pDataChunk: { ((IntPtr)pDataChunk)}, asyncResult: {asyncResult}");
            }
            Debug.Assert(!SentHeaders, "SentHeaders is true.");

            if (StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                // User set 401
                // Using the configured Auth schemes, populate the auth challenge headers. This is for scenarios where
                // Anonymous access is allowed for some resources, but the server later determines that authorization
                // is required for this request.
                HttpListenerContext.SetAuthenticationHeaders();
            }

            // Log headers
            if (NetEventSource.IsEnabled)
            {
                StringBuilder sb = new StringBuilder("HttpListenerResponse Headers:\n");
                for (int i = 0; i < Headers.Count; i++)
                {
                    sb.Append("\t");
                    sb.Append(Headers.GetKey(i));
                    sb.Append(" : ");
                    sb.Append(Headers.Get(i));
                    sb.Append("\n");
                }
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, sb.ToString());
                }
            }
            _responseState = ResponseState.SentHeaders;

            uint            statusCode;
            uint            bytesSent;
            List <GCHandle> pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake);

            try
            {
                if (pDataChunk != null)
                {
                    _nativeResponse.EntityChunkCount = 1;
                    _nativeResponse.pEntityChunks    = pDataChunk;
                }
                else if (asyncResult != null && asyncResult.pDataChunks != null)
                {
                    _nativeResponse.EntityChunkCount = asyncResult.dataChunkCount;
                    _nativeResponse.pEntityChunks    = asyncResult.pDataChunks;
                }
                else
                {
                    _nativeResponse.EntityChunkCount = 0;
                    _nativeResponse.pEntityChunks    = null;
                }
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, "Calling Interop.HttpApi.HttpSendHttpResponse flags:" + flags);
                }
                if (StatusDescription.Length > 0)
                {
                    byte[] statusDescriptionBytes = new byte[WebHeaderEncoding.GetByteCount(StatusDescription)];
                    fixed(byte *pStatusDescription = &statusDescriptionBytes[0])
                    {
                        _nativeResponse.ReasonLength = (ushort)statusDescriptionBytes.Length;
                        WebHeaderEncoding.GetBytes(StatusDescription, 0, statusDescriptionBytes.Length, statusDescriptionBytes, 0);
                        _nativeResponse.pReason = (sbyte *)pStatusDescription;
                        fixed(Interop.HttpApi.HTTP_RESPONSE *pResponse = &_nativeResponse)
                        {
                            statusCode =
                                Interop.HttpApi.HttpSendHttpResponse(
                                    HttpListenerContext.RequestQueueHandle,
                                    HttpListenerRequest.RequestId,
                                    (uint)flags,
                                    pResponse,
                                    null,
                                    &bytesSent,
                                    SafeLocalAllocHandle.Zero,
                                    0,
                                    asyncResult == null ? null : asyncResult._pOverlapped,
                                    null);

                            if (asyncResult != null &&
                                statusCode == Interop.HttpApi.ERROR_SUCCESS &&
                                HttpListener.SkipIOCPCallbackOnSuccess)
                            {
                                asyncResult.IOCompleted(statusCode, bytesSent);
                                // IO operation completed synchronously - callback won't be called to signal completion.
                            }
                        }
                    }
                }
                else
                {
                    fixed(Interop.HttpApi.HTTP_RESPONSE *pResponse = &_nativeResponse)
                    {
                        statusCode =
                            Interop.HttpApi.HttpSendHttpResponse(
                                HttpListenerContext.RequestQueueHandle,
                                HttpListenerRequest.RequestId,
                                (uint)flags,
                                pResponse,
                                null,
                                &bytesSent,
                                SafeLocalAllocHandle.Zero,
                                0,
                                asyncResult == null ? null : asyncResult._pOverlapped,
                                null);

                        if (asyncResult != null &&
                            statusCode == Interop.HttpApi.ERROR_SUCCESS &&
                            HttpListener.SkipIOCPCallbackOnSuccess)
                        {
                            asyncResult.IOCompleted(statusCode, bytesSent);
                            // IO operation completed synchronously - callback won't be called to signal completion.
                        }
                    }
                }
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, "Call to Interop.HttpApi.HttpSendHttpResponse returned:" + statusCode);
                }
            }
            finally
            {
                FreePinnedHeaders(pinnedHeaders);
            }
            return(statusCode);
        }
コード例 #13
0
ファイル: CometClient.cs プロジェクト: SheffieldUni/growl-uos
        /// <summary>

        /// Called once the response has been read. If the transaction is complete, the connection is closed.

        /// If there is an outstanding callback, the connection waits to read it before closing.

        /// </summary>

        /// <param name="iar">The result of the asynchronous operation.</param>

        private void ReadCallback(IAsyncResult iar)

        {
            ResponseState state = null;

            string response = null;



            try

            {
                state = (ResponseState)iar.AsyncState;



                int length = 0;

                if (state != null && state.Stream != null)
                {
                    length = state.Stream.EndRead(iar);
                }



                if (length > 0)

                {
                    response = System.Text.Encoding.UTF8.GetString(state.Buffer, 0, length);



                    // we dont get the length for some reason, so lets add it

                    response = String.Format("{0}\r\n{1}", response.Length.ToString("X"), response);

                    state.HasReceivedData = true;



                    state.Response += response.Trim();;



                    OnResponseReceived(state.Response);

                    state.Response = null;  // reset



                    // keep listening for more

                    AsyncCallback callback = new AsyncCallback(ReadCallback);

                    state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, callback, state);

                    this.isWaiting = true;
                }



                else

                {
                    Utility.WriteDebugInfo("Length was zero - this should not happen");

                    CleanUpSocket(state);

                    OnDisconnected();
                }
            }

            catch

            {
                Utility.WriteDebugInfo("EXCEPTION - CometClient.ReadCallback");



                OnDisconnected();
            }

            finally

            {
                Utility.WriteDebugInfo("CometClient waiting: " + this.isWaiting.ToString());
            }
        }
コード例 #14
0
 public APISetupResponse(ResponseState st, string Message) {
     this.Message = Message;
     this.state = st;
 }
コード例 #15
0
        public void Abort()
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
            try
            {
                if (_responseState >= ResponseState.Closed)
                {
                    return;
                }

                _responseState = ResponseState.Closed;
                HttpListenerContext.Abort();
            }
            finally
            {
                if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
            }
        }
コード例 #16
0
 public ResponseStatus(ResponseState pState)
 {
     State = pState;
 }
コード例 #17
0
	void GetUserInfoResultHandler (ResponseState state, PlatformType type, Hashtable user, Hashtable error)
	{
		print (" =============== GetUserInfoResultHandler");
		if (state == ResponseState.Success)
		{
			print ("get user result :");
			print (MiniJSON.jsonEncode(user));
		}
		else if (state == ResponseState.Fail)
		{
			print ("fail! error code = " + error["error_code"] + "; error msg = " + error["error_msg"]);
		}
		else if (state == ResponseState.Cancel) 
		{
			print ("cancel !");
		}
	}
コード例 #18
0
 public APISetupResponse(ResponseState st, string Message)
 {
     this.Message = Message;
     this.state   = st;
 }
コード例 #19
0
 public void SetResponse(ResponseState state)
 {
     this.Type            = state;
     this.IsValid         = state == ResponseState.Success ? true : false;
     this.IsStopExecuting = state == ResponseState.Success ? false : true;
 }
コード例 #20
0
 public AgvResponsePacket(byte[] data)
     : base("AgvResponsePacket", data)
 {
     this.respType  = data[7];
     this.respState = (ResponseState)data[8];
 }
コード例 #21
0
 public Response(ResponseState state, Request incomingRequest)
 {
     this.State           = state;
     this.IncomingRequest = incomingRequest;
 }
コード例 #22
0
ファイル: PlayerController.cs プロジェクト: ricklove/BushRun
    // Update is called once per frame
    void Update()
    {
        // Input
        upState.ChangeState(Input.GetAxis("Vertical") > 0.01);
        downState.ChangeState(Input.GetAxis("Vertical") < -0.01);

        // Auto move
        var moveDirection = new Vector3(1, 0, 0);

        // Move with keys
        //var moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, 0);

        var move = moveDirection * Time.deltaTime * speed;

        if (health > 0)
        {
            move *= health;
        }
        else
        {
            move = new Vector3();
        }

        // Fly height
        if (upState.State == InputPressState.Begin)
        {
            pathIndex++;
        }
        else if (downState.State == InputPressState.Begin)
        {
            pathIndex--;
        }

        if (pathIndex < 0)
        {
            pathIndex = 0;
        }
        else if (pathIndex >= pathCount)
        {
            pathIndex = pathCount - 1;
        }

        // Move to height
        var pathUnitSize = pathCount > 1 ? maxHeight / (pathCount - 1) : maxHeight;

        var targetHeight = pathIndex * pathUnitSize;
        var actualHeight = transform.localPosition.y;
        var heightDiff = targetHeight - actualHeight;

        var timeToMove = 0.25f;
        var maxMove = pathUnitSize * Time.deltaTime / timeToMove;

        var heightDiffToUse = Mathf.Min(maxMove, Mathf.Abs(heightDiff));
        heightDiffToUse = heightDiff >= 0 ? heightDiffToUse : -heightDiffToUse;

        move += new Vector3(0, heightDiffToUse, 0);

        if (move != new Vector3())
        {
            transform.localPosition += move;
        }

        // Animate
        var headController = GetComponent<HeadSelection>();

        RefreshSpeed();

        // Animation movement z is forward
        if (Mathf.Abs(reportedSpeed - actualSpeed) > 0.05f)
        {
            // Round speed
            //actualSpeed = Mathf.CeilToInt(actualSpeed - 1 / 5) * 5;

            animator.SetFloat("MovementZ", actualSpeed);
            reportedSpeed = actualSpeed;
        }

        if (transform.localPosition.y > 0.1f)
        {
            animator.SetBool("Fly", true);
        }
        else
        {
            animator.SetBool("Fly", false);
        }

        // Move player back to initial points (animation is slowly moving it off)
        childAvatar.transform.localRotation = initialRotation;
        childAvatar.transform.localPosition = initialPosition;

        // Respond to answer
        animator.SetBool("Hurt", false);
        animator.SetBool("Cheer", false);

        if (responseState == ResponseState.Incorrect)
        {
            animator.SetBool("Hurt", true);
            headController.ChangeHead(HeadType.Hurt);
            SoundController.Instance.PlayExplosion();
            ParticleController.Instance.ShowExplosion(transform.position);

            health -= damage;
            if (health <= 0)
            {
                SoundController.Instance.PlayHurt();
                animator.SetBool("Dead", true);
                var oldChoices = ChoiceGUI.Instance.Choices;
                var oldTimeToAnswer = ChoiceGUI.Instance.timeToAnswer;

                Action doContinue = () => {
                    ChoiceGUI.Instance.timeToAnswer = oldTimeToAnswer;
                    ChoiceGUI.Instance.Choices = oldChoices;

                    animator.SetBool("Dead", false);
                    health = 1;
                    HealthBarController.Instance.SetHealth(health);
                };

                Action doStartOver = () => {
                    ChoiceGUI.Instance.timeToAnswer = oldTimeToAnswer;
                    SubjectController.Instance.GoStartOfLevel();

                    animator.SetBool("Dead", false);
                    health = 1;
                    HealthBarController.Instance.SetHealth(health);
                };

                Action doMainMenu = () => {
                    doStartOver();

                    MenuController.Instance.ReturnFromGame();
                };

                ChoiceGUI.Instance.Choices = new Choice[]{
                //new Choice(){ Text="CONTINUE", IsCorrect=true, ChoiceCallback=doContinue },
                    new Choice(){ Text="TRY AGAIN", IsCorrect=true, ChoiceCallback=doStartOver },
                    new Choice(){ Text="MAIN MENU", IsCorrect=true, ChoiceCallback=doMainMenu },
                };

                ChoiceGUI.Instance.timeToAnswer = float.MaxValue;
            }

            HealthBarController.Instance.SetHealth(health);
        }
        else if (responseState == ResponseState.Correct)
        {
            animator.SetBool("Cheer", true);
            headController.ChangeHead(HeadType.Happy);
            SoundController.Instance.PlayCheer();
        }

        responseState = ResponseState.None;
    }
コード例 #23
0
    public void OnError_AuthenticateAnonymous(int statusCode, int reasonCode, string statusMessage, object cbObject)
    {
        m_state    = ResponseState.Error;
        m_response = reasonCode + ":" + statusMessage;
        Debug.LogError("OnError_Authenticate: " + statusMessage);

        if (ErrorHandling.SharedErrorHandling(statusCode, reasonCode, statusMessage, cbObject, gameObject))
        {
            return;
        }

        switch (reasonCode)
        {
        case ReasonCodes.MISSING_IDENTITY_ERROR:
        {
            // Anonymous id is invalid
            // Clear the profile id, generate a new Anonymous id, and re-authenticate
            App.Bc.Client.AuthenticationService.ClearSavedProfileID();
            App.Bc.Client.AuthenticationService.AnonymousId =
                App.Bc.Client.AuthenticationService.GenerateAnonymousId();
            App.Bc.Client
            .AuthenticationService.AuthenticateAnonymous(true, OnSuccess_Authenticate,
                                                         OnError_AuthenticateAnonymous);
            break;
        }

        case ReasonCodes.MISSING_PROFILE_ERROR:
        {
            // Anonymous id doesn't exist in database
            // Must set forceCreate to true
            App.Bc.Client
            .AuthenticationService.AuthenticateAnonymous(true, OnSuccess_Authenticate,
                                                         OnError_AuthenticateAnonymous);
            break;
        }

        case ReasonCodes.SECURITY_ERROR:
        {
            // Credentials are invalid
            // Generate a new Anonymous id, and re-authenticate
            App.Bc.Client.AuthenticationService.AnonymousId =
                App.Bc.Client.AuthenticationService.GenerateAnonymousId();
            App.Bc.Client
            .AuthenticationService.AuthenticateAnonymous(true, OnSuccess_Authenticate,
                                                         OnError_AuthenticateAnonymous);
            break;
        }

        case ReasonCodes.MISSING_REQUIRED_PARAMETER:
        {
            // Anonymous id cannot be blank
            // Generate a new Anonymous id, and re-authenticate
            App.Bc.Client.AuthenticationService.AnonymousId =
                App.Bc.Client.AuthenticationService.GenerateAnonymousId();
            App.Bc.Client
            .AuthenticationService.AuthenticateAnonymous(true, OnSuccess_Authenticate,
                                                         OnError_AuthenticateAnonymous);
            break;
        }

        default:
        {
            // log the reasonCode to your own internal error checking
            ErrorHandling.UncaughtError(statusCode, reasonCode, statusMessage, cbObject, gameObject);

            break;
        }
        }
    }
コード例 #24
0
 public ResponseStatus(ResponseState pState, int pErrorCode)
 {
     State     = pState;
     ErrorCode = pErrorCode;
 }
コード例 #25
0
ファイル: PlayerController.cs プロジェクト: ricklove/BushRun
 public void RespondToAnswer(bool isCorrect)
 {
     responseState = isCorrect ? ResponseState.Correct : ResponseState.Incorrect;
 }
コード例 #26
0
 public ResponseStatus(ResponseState pState, int pErrorCode, string pMessage)
 {
     State     = pState;
     ErrorCode = pErrorCode;
     Message   = pMessage;
 }
コード例 #27
0
 public void Close(byte[] responseEntity, bool willBlock)
 {
     if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"responseEntity={responseEntity},willBlock={willBlock}");
     try
     {
         CheckDisposed();
         if (responseEntity == null)
         {
             throw new ArgumentNullException(nameof(responseEntity));
         }
         if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ResponseState:{_responseState}, BoundaryType:{_boundaryType}, ContentLength:{_contentLength}");
         if (_responseState < ResponseState.SentHeaders && _boundaryType != BoundaryType.Chunked)
         {
             ContentLength64 = responseEntity.Length;
         }
         EnsureResponseStream();
         if (willBlock)
         {
             try
             {
                 _responseStream.Write(responseEntity, 0, responseEntity.Length);
             }
             catch (Win32Exception)
             {
             }
             finally
             {
                 _responseStream.Close();
                 _responseState = ResponseState.Closed;
                 HttpListenerContext.Close();
             }
         }
         else
         {
             _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
         }
     }
     finally
     {
         if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
     }
 }
コード例 #28
0
 public ResponseStatus(ResponseState pState, string pMessage)
 {
     State   = pState;
     Message = pMessage;
 }
コード例 #29
0
ファイル: Response.cs プロジェクト: Demenovich-A-J/ATS
 public Response(ResponseState state, PhoneNumber source)
 {
     State = state;
     Source = source;
 }
コード例 #30
0
        public ResponseState ProcessDownload(HttpResponse objResponse)
        {
            ResponseState resultState = ResponseState.None;

            // Long Arrays for Range values:
            // ...Begin() contains start positions for each requested Range
            long[] alRequestedRangesBegin = new long[1];
            alRequestedRangesBegin[0] = _responseData.RangeBegin;

            // ...End() contains end positions for each requested Range
            long[] alRequestedRangesEnd = new long[1];
            alRequestedRangesEnd[0] = _responseData.RangeEnd;

            // Response Header value: Content Length...
            int iResponseContentLength = 0;

            // The Stream we//re using to download the file in chunks...
            System.IO.Stream objStream;
            // Total Bytes to read (per requested range)
            int iBytesToRead;

            // Size of the Buffer for chunk-wise reading
            int iBufferSize = 5120;

            // The Buffer itself
            byte[] bBuffer = new byte[iBufferSize];
            // Amount of Bytes read
            int iLengthOfReadChunk = -1;

            // Indicates if the download was interrupted
            bool bDownloadBroken = false;

            // Indicates if this is a multipart range request
            bool bMultipart = false;

            // Loop counter used to iterate through the ranges
            int iLoop;

            // Content-Disposition value
            string Content_Disposition_File = "attachment; filename=" + _responseData.FileHeaderName;


            if (!(_responseData.HttpMethod.Equals(HTTP_METHOD_GET) ||
                  _responseData.HttpMethod.Equals(HTTP_METHOD_HEAD)))
            {
                // Currently, only the GET and HEAD methods
                // are supported...
                objResponse.StatusCode = 501;                  // Not implemented
            }
            else
            {
                // Preliminary checks where successful...
                if (_responseData.RangeRequest)
                {
                    // This is a Range request...

                    // if the Range arrays contain more than one entry,
                    // it even is a multipart range request...
                    bMultipart = (alRequestedRangesBegin.GetUpperBound(0) > 0);

                    // Loop through each Range to calculate the entire Response length
                    for (iLoop = alRequestedRangesBegin.GetLowerBound(0); iLoop <= alRequestedRangesBegin.GetUpperBound(0); iLoop++)
                    {
                        // The length of the content (for this range)
                        iResponseContentLength += Convert.ToInt32(alRequestedRangesEnd[iLoop] - alRequestedRangesBegin[iLoop]) + 1;

                        if (bMultipart)
                        {
                            //
                            iResponseContentLength += HTTP_HEADER_Content_Disposition.Length;
                            // if this is a multipart range request, calculate
                            // the length of the intermediate headers to send
                            iResponseContentLength += MULTIPART_BOUNDARY.Length;
                            iResponseContentLength += _responseData.ContentType.Length;
                            iResponseContentLength += alRequestedRangesBegin[iLoop].ToString().Length;
                            iResponseContentLength += alRequestedRangesEnd[iLoop].ToString().Length;

                            // DataLength = Total size
                            iResponseContentLength += _responseData.DataLength.ToString().Length;

                            // 49 is the length of line break and other
                            // needed characters in one multipart header
                            iResponseContentLength += 49;
                        }
                    }

                    if (bMultipart)
                    {
                        // if this is a multipart range request,
                        // we must also calculate the length of
                        // the last intermediate header we must send
                        iResponseContentLength += MULTIPART_BOUNDARY.Length;
                        // 8 is the length of dash and line break characters
                        iResponseContentLength += 8;
                    }
                    else
                    {
                        // This is no multipart range request, so
                        // we must indicate the response Range of
                        // in the initial HTTP Header
                        // DataLength = Total size
                        objResponse.AppendHeader(HTTP_HEADER_CONTENT_RANGE, "bytes " +
                                                 alRequestedRangesBegin[0].ToString() + "-" +
                                                 alRequestedRangesEnd[0].ToString() + "/" +
                                                 _responseData.DataLength.ToString());
                    }

                    // Range response
                    objResponse.StatusCode = 206;                     // Partial Response
                }
                else
                {
                    // This is not a Range request, or the requested Range entity ID
                    // does not match the current entity ID, so start a new download

                    // Indicate the file's complete size as content length
                    // DataLength = Total size
                    iResponseContentLength = Convert.ToInt32(_responseData.DataLength);

                    // Return a normal OK status...
                    objResponse.StatusCode = 200;
                }


                // Write file name into the Response
                objResponse.AppendHeader(HTTP_HEADER_Content_Disposition, Content_Disposition_File);

                // Write the content length into the Response
                objResponse.AppendHeader(HTTP_HEADER_CONTENT_LENGTH, iResponseContentLength.ToString());

                // Write the Last-Modified Date into the Response
                objResponse.AppendHeader(HTTP_HEADER_LAST_MODIFIED, _responseData.LastWriteTimeUTC.ToString("r"));

                // Tell the client software that we accept Range request
                objResponse.AppendHeader(HTTP_HEADER_ACCEPT_RANGES, HTTP_HEADER_ACCEPT_RANGES_BYTES);

                // Write the file//s Entity Tag into the Response (in quotes!)
                objResponse.AppendHeader(HTTP_HEADER_ENTITY_TAG, "\"" + _responseData.EntityTag + "\"");


                // Write the Content Type into the Response
                if (bMultipart)
                {
                    // Multipart messages have this special Type.
                    // In this case, the file//s actual mime type is
                    // written into the Response at a later time...
                    objResponse.ContentType = MULTIPART_CONTENTTYPE;
                }
                else
                {
                    // Single part messages have the files content type...
                    objResponse.ContentType = _responseData.ContentType;
                }


                if (_responseData.HttpMethod.Equals(HTTP_METHOD_HEAD))
                {
                    // Only the HEAD was requested, so we can quit the Response right here...
                }
                else
                {
                    // Flush the HEAD information to the client...
                    objResponse.Flush();

                    // Download is in progress...
                    resultState = ResponseState.InProgress;

                    // The steram
                    objStream = _responseData.DataStream;

                    if (!_responseData.ApplyRangeToStream)
                    {
                        // first range only
                        iLoop = 0;

                        // Calculate the total amount of bytes for first range only
                        iBytesToRead = Convert.ToInt32(alRequestedRangesEnd[iLoop] - alRequestedRangesBegin[iLoop]) + 1;

                        // sending header for multipart request
                        if (bMultipart)
                        {
                            // if this is a multipart response, we must add
                            // certain headers before streaming the content:

                            // The multipart boundary
                            objResponse.Output.WriteLine("--" + MULTIPART_BOUNDARY);

                            // The mime type of this part of the content
                            objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_TYPE + ": " + _responseData.ContentType);

                            // The actual range
                            // // DataLength = Total size
                            objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_RANGE + ": bytes " +
                                                         alRequestedRangesBegin[iLoop].ToString() + "-" +
                                                         alRequestedRangesEnd[iLoop].ToString() + "/" +
                                                         _responseData.DataLength.ToString());

                            // Indicating the end of the intermediate headers
                            objResponse.Output.WriteLine();
                        }

                        // flush the data

                        // Declare variables
                        int readed = -1;

#if dotNET20sp1
                        if (_responseData.IsDataFile)
                        {
                            // send file content directly
                            objResponse.TransmitFile(_responseData.FileName);
                        }
                        else
#endif
                        // Get the response stream for reading
                        // Read the stream and write it into memory
                        while ((int)(readed = objStream.Read(bBuffer, 0, bBuffer.Length)) > 0)
                        {
                            if (objResponse.IsClientConnected)
                            {
                                // write to response
                                objResponse.OutputStream.Write(bBuffer, 0, readed);

                                // send response
                                objResponse.Flush();
                            }
                            else
                            {
                                bDownloadBroken = true;
                                break;
                            }
                        }

                        // In Multipart responses, mark the end of the part
                        if (bMultipart)
                        {
                            objResponse.Output.WriteLine();
                        }

                        // No need to proceed to the next part if the
                        // client was disconnected
                        if (bDownloadBroken)
                        {
                            //break;
                        }
                        // done!
                    }
                    else
                    {
                        // Now, for each requested range, stream the chunks to the client:
                        for (iLoop = alRequestedRangesBegin.GetLowerBound(0); iLoop <= alRequestedRangesBegin.GetUpperBound(0); iLoop++)
                        {
                            // Move the stream to the desired start position...
                            objStream.Seek(alRequestedRangesBegin[iLoop], SeekOrigin.Begin);

                            // Calculate the total amount of bytes for this range
                            iBytesToRead = Convert.ToInt32(alRequestedRangesEnd[iLoop] - alRequestedRangesBegin[iLoop]) + 1;

                            if (bMultipart)
                            {
                                // if this is a multipart response, we must add
                                // certain headers before streaming the content:

                                // The multipart boundary
                                objResponse.Output.WriteLine("--" + MULTIPART_BOUNDARY);

                                // The mime type of this part of the content
                                objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_TYPE + ": " + _responseData.ContentType);

                                // The actual range
                                // // DataLength = Total size
                                objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_RANGE + ": bytes " +
                                                             alRequestedRangesBegin[iLoop].ToString() + "-" +
                                                             alRequestedRangesEnd[iLoop].ToString() + "/" +
                                                             _responseData.DataLength.ToString());

                                /*objResponse.AppendHeader(HTTP_HEADER_CONTENT_RANGE,": bytes " +
                                 *      alRequestedRangesBegin[iLoop].ToString() + "-" +
                                 *      alRequestedRangesend[iLoop].ToString() + "/" +
                                 *      objFile.Length.ToString());
                                 */
                                // Indicating the end of the intermediate headers
                                objResponse.Output.WriteLine();
                            }

#if dotNET20sp1
                            if (_responseData.IsDataFile)
                            {
                                // send file content directly
                                objResponse.TransmitFile(_responseData.FileName, alRequestedRangesBegin[iLoop], iBytesToRead);
                            }
                            else
#endif
                            // Now stream the range to the client...
                            while (iBytesToRead > 0)
                            {
                                if (objResponse.IsClientConnected)
                                {
                                    // Read a chunk of bytes from the stream
                                    iLengthOfReadChunk = objStream.Read(bBuffer, 0, Math.Min(bBuffer.Length, iBytesToRead));

                                    // Write the data to the current output stream.
                                    objResponse.OutputStream.Write(bBuffer, 0, iLengthOfReadChunk);

                                    // Flush the data to the HTML output.
                                    objResponse.Flush();

                                    // Clear the buffer
                                    //bBuffer=new byte[iBufferSize];

                                    // Reduce BytesToRead
                                    iBytesToRead -= iLengthOfReadChunk;
                                }
                                else
                                {
                                    // The client was or has disconneceted from the server... stop downstreaming...
                                    iBytesToRead    = -1;
                                    bDownloadBroken = true;
                                }
                            }

                            // In Multipart responses, mark the end of the part
                            if (bMultipart)
                            {
                                objResponse.Output.WriteLine();
                            }

                            // No need to proceed to the next part if the
                            // client was disconnected
                            if (bDownloadBroken)
                            {
                                break;
                            }
                        }
                    }
                    // At this point, the response was finished or cancelled...

                    if (bDownloadBroken)
                    {
                        // Download is broken...
                        resultState = ResponseState.Broken;
                    }
                    else
                    {
                        if (bMultipart)
                        {
                            // In multipart responses, close the response once more with
                            // the boundary and line breaks
                            objResponse.Output.WriteLine("--" + MULTIPART_BOUNDARY + "--");
                            objResponse.Output.WriteLine();
                        }

                        // The download was finished
                        resultState = ResponseState.Finished;
                    }

                    // the data stream now can be closed
                    objStream.Close();
                }
            }

            //====== return download state ======
            return(resultState);
        }
コード例 #31
0
    /**
     * 获取微信个人信息成功回调,登录
     *
     */
    public void getUserInforCallback(int reqID, ResponseState state, PlatformType type, Hashtable data)
    {
        //TipsManagerScript.getInstance ().setTips ("获取个人信息成功");

        if (state == ResponseState.Fail)
        {
            if (GlobalDataScript.inAppPay)
            {
                TipsManagerScript.getInstance().setTips("微信登录失败,以游客身份登陆");
                debugLogin();
            }
            else
            {
                TipsManagerScript.getInstance().setTips("微信登录失败");
            }
            return;
        }

        if (data != null)
        {
            UnityEngine.Debug.Log(data.toJson());
            LoginVo loginvo = new LoginVo();
            try {
                loginvo.openId   = (string)data["openid"];
                loginvo.nickName = (string)data["nickname"];
                loginvo.headIcon = (string)data["headimgurl"];
                loginvo.unionid  = (string)data["unionid"];
                loginvo.province = (string)data["province"];
                loginvo.city     = (string)data["city"];
                string sex = data["sex"].ToString();
                loginvo.sex = int.Parse(sex);
                loginvo.IP  = GlobalDataScript.getInstance().getIpAddress();
                String msg = JsonMapper.ToJson(loginvo);

                CustomSocket.getInstance().sendMsg(new LoginRequest(msg));

                GlobalDataScript.loginVo                          = loginvo;
                GlobalDataScript.loginResponseData                = new AvatarVO();
                GlobalDataScript.loginResponseData.account        = new Account();
                GlobalDataScript.loginResponseData.account.city   = loginvo.city;
                GlobalDataScript.loginResponseData.account.openid = loginvo.openId;
                UnityEngine.Debug.Log(" loginvo.nickName:" + loginvo.nickName);
                GlobalDataScript.loginResponseData.account.nickname = loginvo.nickName;
                GlobalDataScript.loginResponseData.account.headicon = loginvo.headIcon;
                GlobalDataScript.loginResponseData.account.unionid  = loginvo.city;
                GlobalDataScript.loginResponseData.account.sex      = loginvo.sex;
                GlobalDataScript.loginResponseData.IP = loginvo.IP;
            } catch (Exception e) {
                UnityEngine.Debug.Log("微信接口有变动!" + e.Message);
                TipsManagerScript.getInstance().setTips("请先打开你的微信客户端");
                return;
            }
        }
        else
        {
            if (GlobalDataScript.inAppPay)
            {
                TipsManagerScript.getInstance().setTips("微信登录失败,以游客身份登陆");
                debugLogin();
            }
            else
            {
                TipsManagerScript.getInstance().setTips("微信登录失败");
            }
        }
    }
コード例 #32
0
/*
 * 12.3
 * HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
 * The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:
 *
 #define HTTP_SEND_RESPONSE_FLAG_DISCONNECT          0x00000001
 #define HTTP_SEND_RESPONSE_FLAG_MORE_DATA           0x00000002
 #define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER          0x00000004
 #define HTTP_SEND_RESPONSE_FLAG_VALID               0x00000007
 *
 * HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
 *  specifies that the network connection should be disconnected immediately after
 *  sending the response, overriding the HTTP protocol's persistent connection features.
 * HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
 *  specifies that additional entity body data will be sent by the caller. Thus,
 *  the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
 * HTTP_SEND_RESPONSE_RAW_HEADER:
 *  specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
 *  a call to HttpSendHttpResponse() in order to bypass normal header processing. The
 *  actual HTTP header will be generated by the application and sent as entity body.
 *  This flag should be passed on the first call to HttpSendResponseEntityBody, and
 *  not after. Thus, flag is not applicable to HttpSendHttpResponse.
 */
        internal unsafe uint SendHeaders(UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK *pDataChunk,
                                         HttpResponseStreamAsyncResult asyncResult,
                                         UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags,
                                         bool isWebSocketHandshake)
        {
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() pDataChunk:" + ValidationHelper.ToString((IntPtr)pDataChunk) + " asyncResult:" + ValidationHelper.ToString(asyncResult));
            GlobalLog.Assert(!SentHeaders, "HttpListenerResponse#{0}::SendHeaders()|SentHeaders is true.", ValidationHelper.HashString(this));

            if (StatusCode == (int)HttpStatusCode.Unauthorized)   // User set 401
            // Using the configured Auth schemes, populate the auth challenge headers. This is for scenarios where
            // Anonymous access is allowed for some resources, but the server later determines that authorization
            // is required for this request.
            {
                HttpListenerContext.SetAuthenticationHeaders();
            }

            // Log headers
            if (Logging.On)
            {
                StringBuilder sb = new StringBuilder("HttpListenerResponse Headers:\n");
                for (int i = 0; i < Headers.Count; i++)
                {
                    sb.Append("\t");
                    sb.Append(Headers.GetKey(i));
                    sb.Append(" : ");
                    sb.Append(Headers.Get(i));
                    sb.Append("\n");
                }
                Logging.PrintInfo(Logging.HttpListener, this, ".ctor", sb.ToString());
            }
            m_ResponseState = ResponseState.SentHeaders;

            /*
             * if (m_BoundaryType==BoundaryType.Raw) {
             *  use HTTP_SEND_RESPONSE_FLAG_RAW_HEADER;
             * }
             */
            uint            statusCode;
            uint            bytesSent;
            List <GCHandle> pinnedHeaders = SerializeHeaders(ref m_NativeResponse.Headers, isWebSocketHandshake);

            try {
                if (pDataChunk != null)
                {
                    m_NativeResponse.EntityChunkCount = 1;
                    m_NativeResponse.pEntityChunks    = pDataChunk;
                }
                else if (asyncResult != null && asyncResult.pDataChunks != null)
                {
                    m_NativeResponse.EntityChunkCount = asyncResult.dataChunkCount;
                    m_NativeResponse.pEntityChunks    = asyncResult.pDataChunks;
                }
                else
                {
                    m_NativeResponse.EntityChunkCount = 0;
                    m_NativeResponse.pEntityChunks    = null;
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() calling UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse flags:" + flags);
                if (StatusDescription.Length > 0)
                {
                    byte[] statusDescriptionBytes = new byte[WebHeaderCollection.HeaderEncoding.GetByteCount(StatusDescription)];
                    fixed(byte *pStatusDescription = statusDescriptionBytes)
                    {
                        m_NativeResponse.ReasonLength = (ushort)statusDescriptionBytes.Length;
                        WebHeaderCollection.HeaderEncoding.GetBytes(StatusDescription, 0, statusDescriptionBytes.Length, statusDescriptionBytes, 0);
                        m_NativeResponse.pReason = (sbyte *)pStatusDescription;
                        fixed(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE *pResponse = &m_NativeResponse)
                        {
                            if (asyncResult != null)
                            {
                                HttpListenerContext.EnsureBoundHandle();
                            }
                            statusCode =
                                UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse(
                                    HttpListenerContext.RequestQueueHandle,
                                    HttpListenerRequest.RequestId,
                                    (uint)flags,
                                    pResponse,
                                    null,
                                    &bytesSent,
                                    SafeLocalFree.Zero,
                                    0,
                                    asyncResult == null ? null : asyncResult.m_pOverlapped,
                                    null);

                            if (asyncResult != null &&
                                statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
                                HttpListener.SkipIOCPCallbackOnSuccess)
                            {
                                asyncResult.IOCompleted(statusCode, bytesSent);
                                // IO operation completed synchronously - callback won't be called to signal completion.
                            }
                        }
                    }
                }
                else
                {
                    fixed(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE *pResponse = &m_NativeResponse)
                    {
                        if (asyncResult != null)
                        {
                            HttpListenerContext.EnsureBoundHandle();
                        }
                        statusCode =
                            UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse(
                                HttpListenerContext.RequestQueueHandle,
                                HttpListenerRequest.RequestId,
                                (uint)flags,
                                pResponse,
                                null,
                                &bytesSent,
                                SafeLocalFree.Zero,
                                0,
                                asyncResult == null ? null : asyncResult.m_pOverlapped,
                                null);

                        if (asyncResult != null &&
                            statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
                            HttpListener.SkipIOCPCallbackOnSuccess)
                        {
                            asyncResult.IOCompleted(statusCode, bytesSent);
                            // IO operation completed synchronously - callback won't be called to signal completion.
                        }
                    }
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() call to UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse returned:" + statusCode);
            }
            finally {
                FreePinnedHeaders(pinnedHeaders);
            }
            return(statusCode);
        }
コード例 #33
0
        internal Interop.HttpApi.HTTP_FLAGS ComputeHeaders()
        {
            Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE;
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this);
            }
            Debug.Assert(!ComputedHeaders, "ComputedHeaders is true.");
            _responseState = ResponseState.ComputedHeaders;

            ComputeCoreHeaders();

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this,
                                    $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} _keepAlive: {_keepAlive}");
            }
            if (_boundaryType == BoundaryType.None)
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    _keepAlive = false;
                }
                else
                {
                    _boundaryType = BoundaryType.Chunked;
                }
                if (CanSendResponseBody(_httpContext.Response.StatusCode))
                {
                    _contentLength = -1;
                }
                else
                {
                    ContentLength64 = 0;
                }
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"flags:{flags} _BoundaryType:{_boundaryType} _contentLength:{_contentLength} _keepAlive: {_keepAlive}");
            }
            if (_boundaryType == BoundaryType.ContentLength)
            {
                Headers[HttpResponseHeader.ContentLength] = _contentLength.ToString("D", NumberFormatInfo.InvariantInfo);
                if (_contentLength == 0)
                {
                    flags = Interop.HttpApi.HTTP_FLAGS.NONE;
                }
            }
            else if (_boundaryType == BoundaryType.Chunked)
            {
                Headers[HttpResponseHeader.TransferEncoding] = "chunked";
            }
            else if (_boundaryType == BoundaryType.None)
            {
                flags = Interop.HttpApi.HTTP_FLAGS.NONE; // seems like HTTP_SEND_RESPONSE_FLAG_MORE_DATA but this hangs the app;
            }
            else
            {
                _keepAlive = false;
            }
            if (!_keepAlive)
            {
                Headers.Add(HttpResponseHeader.Connection, "close");
                if (flags == Interop.HttpApi.HTTP_FLAGS.NONE)
                {
                    flags = Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
                }
            }
            else
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    Headers[HttpResponseHeader.KeepAlive] = "true";
                }
            }
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"flags:{flags} _BoundaryType:{_boundaryType} _contentLength:{_contentLength} _keepAlive: {_keepAlive}");
            }
            return(flags);
        }
コード例 #34
0
        internal UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS ComputeHeaders()
        {
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE;
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders()");
            GlobalLog.Assert(!ComputedHeaders, "HttpListenerResponse#{0}::ComputeHeaders()|ComputedHeaders is true.", ValidationHelper.HashString(this));
            m_ResponseState = ResponseState.ComputedHeaders;

            /*
             * // here we would check for BoundaryType.Raw, in this case we wouldn't need to do anything
             * if (m_BoundaryType==BoundaryType.Raw) {
             *  return flags;
             * }
             */

            ComputeCoreHeaders();

            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders() flags:" + flags + " m_BoundaryType:" + m_BoundaryType + " m_ContentLength:" + m_ContentLength + " m_KeepAlive:" + m_KeepAlive);
            if (m_BoundaryType == BoundaryType.None)
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    //
                    m_KeepAlive = false;
                }
                else
                {
                    m_BoundaryType = BoundaryType.Chunked;
                }
                if (CanSendResponseBody(m_HttpContext.Response.StatusCode))
                {
                    m_ContentLength = -1;
                }
                else
                {
                    ContentLength64 = 0;
                }
            }

            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders() flags:" + flags + " m_BoundaryType:" + m_BoundaryType + " m_ContentLength:" + m_ContentLength + " m_KeepAlive:" + m_KeepAlive);
            if (m_BoundaryType == BoundaryType.ContentLength)
            {
                Headers.SetInternal(HttpResponseHeader.ContentLength, m_ContentLength.ToString("D", NumberFormatInfo.InvariantInfo));
                if (m_ContentLength == 0)
                {
                    flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE;
                }
            }
            else if (m_BoundaryType == BoundaryType.Chunked)
            {
                Headers.SetInternal(HttpResponseHeader.TransferEncoding, HttpWebRequest.ChunkedHeader);
            }
            else if (m_BoundaryType == BoundaryType.None)
            {
                flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE; // seems like HTTP_SEND_RESPONSE_FLAG_MORE_DATA but this hangs the app;
            }
            else
            {
                m_KeepAlive = false;
            }
            if (!m_KeepAlive)
            {
                Headers.Add(HttpResponseHeader.Connection, "close");
                if (flags == UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE)
                {
                    flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
                }
            }
            else
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    Headers.SetInternal(HttpResponseHeader.KeepAlive, "true");
                }
            }
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders() flags:" + flags + " m_BoundaryType:" + m_BoundaryType + " m_ContentLength:" + m_ContentLength + " m_KeepAlive:" + m_KeepAlive);
            return(flags);
        }
コード例 #35
0
        /// <summary>
        /// 获取用户基本信息(包括UnionID机制)
        /// </summary>
        /// <param name="access_Token">微信号access_Token</param>
        /// <param name="openID">用户openID</param>
        /// <param name="lang">语言</param>
        /// <param name="state">返回状态</param>
        /// <returns></returns>
        public static UserDetail GetUserDetail(string access_Token, string openID, Lang lang, out ResponseState state)
        {
            state = null;
            string url      = Setting.ApiUrl + "cgi-bin/user/info?access_token=" + access_Token + "openid=" + openID + "&lang=" + lang.ToString();
            string response = DownJsonData(url);

            try
            {
                return(DeSerialize <UserDetail>(response));
            }
            catch (Exception ex)
            {
                state = DeSerialize <ResponseState>(response);
                return(null);
            }
        }
コード例 #36
0
 public Response() { _state = ResponseState.SUCCESS; }
コード例 #37
0
 private void OnAuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable data)
 {
     throw new NotImplementedException();
 }
コード例 #38
0
ファイル: WechatOperateScript.cs プロジェクト: iuvei/PKGame
    /**
     * 获取微信个人信息成功回调,登录
     *
     */
    public void authResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable data)
    {
        //TipsManagerScript.getInstance ().setTips ("获取个人信息成功");
        debug_Text.text = ("成功回调微信信息,开始登录");
        //TipsManagerScript.getInstance ().setTipsBig (data.toJson());
                #if UNITY_IOS
        shareSdk.GetUserInfo(PlatformType.WeChat);
        return;
                #else
        data = shareSdk.GetAuthInfo(PlatformType.WeChat);
                #endif
        if (data != null)
        {
            LoginVo loginvo = new LoginVo();
            try {
                MyDebug.Log(data.toJson());
                //TipsManagerScript.getInstance ().setTipsBig (data.toJson());

                loginvo.openId   = (string)data ["openid"];
                loginvo.nickName = (string)data ["nickname"];
                loginvo.headIcon = (string)data ["icon"];
                loginvo.unionid  = (string)data ["unionid"];
                loginvo.province = (string)data ["province"];
                loginvo.city     = (string)data ["city"];
                string sex = data ["gender"].ToString();
                loginvo.sex = int.Parse(sex);
                loginvo.IP  = GlobalDataScript.getInstance().getIpAddress();
                String msg = JsonMapper.ToJson(loginvo);

                PlayerPrefs.SetString("loginInfo", msg);

                CustomSocket.getInstance().sendMsg(new LoginRequest(msg));

                /*
                 * GlobalDataScript.loginVo = loginvo;
                 * GlobalDataScript.loginResponseData = new AvatarVO ();
                 * GlobalDataScript.loginResponseData.account = new Account ();
                 * GlobalDataScript.loginResponseData.account.city = loginvo.city;
                 * GlobalDataScript.loginResponseData.account.openid = loginvo.openId;
                 * MyDebug.Log(" loginvo.nickName:"+loginvo.nickName);
                 * GlobalDataScript.loginResponseData.account.nickname = loginvo.nickName;
                 * GlobalDataScript.loginResponseData.account.headicon = loginvo.headIcon;
                 * GlobalDataScript.loginResponseData.account.unionid = loginvo.city;
                 * GlobalDataScript.loginResponseData.account.sex = loginvo.sex;
                 * GlobalDataScript.loginResponseData.IP = loginvo.IP;
                 *
                 * //加载头像
                 * if(GlobalDataScript.loginVo.sex == 2){
                 *      GlobalDataScript.getInstance().headSprite = Resources.Load ("xianlai/public_ui/head_img_female", typeof(Sprite)) as Sprite;
                 * }else {
                 *      GlobalDataScript.getInstance().headSprite = Resources.Load ("xianlai/public_ui/head_img_male", typeof(Sprite)) as Sprite;
                 * }
                 */
            } catch (Exception e) {
                MyDebug.Log("微信接口有变动!" + e.Message);
                TipsManagerScript.getInstance().setTips("微信接口有变动!" + e.Message);
                return;
            }
        }
        else
        {
            TipsManagerScript.getInstance().setTips("微信登录失败");
        }
    }
コード例 #39
0
ファイル: SocketBase.cs プロジェクト: mmarzz/AutoCSer
 /// <summary>
 /// 输出错误状态
 /// </summary>
 /// <param name="state">错误状态</param>
 internal abstract void ResponseErrorIdentity(ResponseState state);
コード例 #40
0
ファイル: Socket.cs プロジェクト: zhangb12465/AutoCSer
        /// <summary>
        /// HTTP 响应头部输出
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private bool responseHeader(ref Response response)
        {
            try
            {
                if (!response.IsFile)
                {
                    ResponseError(ResponseState.NotFound404);
                    return true;
                }
                System.Net.Sockets.Socket socket;
                ResponseFlag responseFlag = response.Flag;
                if (response.Body.Length != 0 && Header.IsKeepAlive != 0 && (responseFlag & ResponseFlag.HeaderSize) != 0 && Header.IsRange == 0 && Header.Method != MethodType.HEAD)
                {
                    if ((socket = Socket) == null) return false;
                    Data = response.Body;
                    Data.MoveStart(-response.HeaderSize);
                    SendType = SendType.Next;
                    Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                    SocketError socketError;
                    IAsyncResult async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                    if (socketError == SocketError.Success)
                    {
                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                        return true;
                    }
                    return false;
#else
                    while (Interlocked.CompareExchange(ref sendAsyncLock, 1, 0) != 0) Thread.Sleep(0);
                    sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                    if (socket.SendAsync(sendAsyncEventArgs))
                    {
                        Http.Header.ReceiveTimeout.Push(this, socket);
                        Interlocked.Exchange(ref sendAsyncLock, 0);
                        return true;
                    }
                    Interlocked.Exchange(ref sendAsyncLock, 0);
                    if (--sendDepth == 0)
                    {
                        sendDepth = maxSendDepth;
                        OnSendTask.Task.Add(this);
                        return true;
                    }
                    return onSend();
#endif
                }
                ResponseSize = response.BodySize;
                fixed (byte* headerBufferFixed = Header.Buffer.Buffer)
                {
                    byte* responseSizeFixed = headerBufferFixed + (Header.Buffer.StartIndex + Http.Header.ReceiveBufferSize);
                    RangeLength responseSizeIndex, bodySizeIndex = new RangeLength(), rangeStartIndex = new RangeLength(), rangeEndIndex = new RangeLength();
                    ResponseState state = response.ResponseState;
                    if (Header.IsRange != 0 && (responseFlag & ResponseFlag.IsPool) != 0)
                    {
                        if (Header.IsFormatRange != 0 || Header.FormatRange(ResponseSize))
                        {
                            if (state == ResponseState.Ok200)
                            {
                                long rangeStart = Header.RangeStart, rangeEnd = Header.RangeEnd;
                                rangeStartIndex = Number.ToBytes((ulong)rangeStart, responseSizeFixed + 20 * 2);
                                rangeEndIndex = Number.ToBytes((ulong)rangeEnd, responseSizeFixed + 20 * 3);
                                bodySizeIndex = Number.ToBytes((ulong)ResponseSize, responseSizeFixed + 20);
                                response.State = state = ResponseState.PartialContent206;
                                ResponseSize = Header.RangeSize;
                            }
                        }
                        else
                        {
                            ResponseSize = 0;
                            ResponseError(ResponseState.RangeNotSatisfiable416);
                            return true;
                        }
                    }
                    if ((ulong)ResponseSize < 10)
                    {
                        *responseSizeFixed = (byte)((int)ResponseSize + '0');
                        responseSizeIndex = new RangeLength(0, 1);
                    }
                    else responseSizeIndex = Number.ToBytes((ulong)ResponseSize, responseSizeFixed);
                    ResponseStateAttribute stateAttribute = EnumAttribute<ResponseState, ResponseStateAttribute>.Array((byte)state);
                    if (stateAttribute == null) stateAttribute = EnumAttribute<ResponseState, ResponseStateAttribute>.Array((byte)ResponseState.ServerError500);
                    int index = httpVersionSize + stateAttribute.Text.Length + contentLengthSize + responseSizeIndex.Length + 2 + 2;
                    if (state == ResponseState.PartialContent206)
                    {
                        index += rangeSize + rangeStartIndex.Length + rangeEndIndex.Length + bodySizeIndex.Length + 2 + 2;
                    }
                    Cookie cookie = null;
                    SubBuffer.PoolBufferFull buffer = GetBuffer(index = GetResponseHeaderIndex(response, index, ref cookie));
                    fixed (byte* bufferFixed = buffer.Buffer)
                    {
                        byte* bufferStart = bufferFixed + buffer.StartIndex, write = bufferStart + httpVersionSize;
                        writeHttpVersion(bufferStart);
                        stateAttribute.Write(write);
                        writeContentLength(write += stateAttribute.Text.Length);
                        Memory.SimpleCopyNotNull64(responseSizeFixed + responseSizeIndex.Start, write += contentLengthSize, responseSizeIndex.Length);
                        *(short*)(write += responseSizeIndex.Length) = 0x0a0d;
                        write += sizeof(short);
                        if (state == ResponseState.PartialContent206)
                        {
                            writeRange(write);
                            Memory.SimpleCopyNotNull64(responseSizeFixed + (rangeStartIndex.Start + 20 * 2), write += rangeSize, rangeStartIndex.Length);
                            *(write += rangeStartIndex.Length) = (byte)'-';
                            Memory.SimpleCopyNotNull64(responseSizeFixed + (rangeEndIndex.Start + 20 * 3), ++write, rangeEndIndex.Length);
                            *(write += rangeEndIndex.Length) = (byte)'/';
                            Memory.SimpleCopyNotNull64(responseSizeFixed + (bodySizeIndex.Start + 20), ++write, bodySizeIndex.Length);
                            *(short*)(write += bodySizeIndex.Length) = 0x0a0d;
                            write += sizeof(short);
                        }
                        index = (int)(CreateResponseHeader(response, cookie, write, index) - bufferStart);
                        //                    if (checkIndex != index)
                        //                    {
                        //                        Server.RegisterServer.TcpServer.Log.add(Log.Type.Fatal, "responseHeader checkIndex[" + checkIndex.toString() + "] != index[" + index.toString() + @"]
                        //" + System.Text.Encoding.ASCII.GetString(buffer.Buffer, buffer.StartIndex, index));
                        //                    }
                        if (ResponseSize != 0)
                        {
                            switch (response.Type)
                            {
                                case ResponseType.ByteArray:
                                    if (buffer.Length - index >= (int)ResponseSize)
                                    {
                                        System.Buffer.BlockCopy(response.Body.Array, state == ResponseState.PartialContent206 ? (int)Header.RangeStart : 0, buffer.Buffer, buffer.StartIndex + index, (int)ResponseSize);
                                        index += (int)ResponseSize;
                                        ResponseSize = 0;
                                    }
                                    break;
                                case ResponseType.SubByteArray:
                                    if (Header.IsKeepAlive != 0 && (responseFlag & ResponseFlag.CanHeaderSize) != 0 && index <= response.Body.Start && Header.IsRange == 0)
                                    {
                                        if ((socket = Socket) == null) return false;
                                        fixed (byte* bodyFixed = response.Body.Array) Memory.CopyNotNull(bufferStart, bodyFixed + response.Body.Start - index, index);
                                        response.SetHeaderSize(index);

                                        Data = response.Body;
                                        Data.MoveStart(-response.HeaderSize);
                                        SendType = SendType.Next;
                                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                                    SocketError socketError;
                                    IAsyncResult async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                                    if (socketError == SocketError.Success)
                                    {
                                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                        return true;
                                    }
                                    return false;
#else
                                        while (Interlocked.CompareExchange(ref sendAsyncLock, 1, 0) != 0) Thread.Sleep(0);
                                        sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                                        if (socket.SendAsync(sendAsyncEventArgs))
                                        {
                                            Http.Header.ReceiveTimeout.Push(this, socket);
                                            Interlocked.Exchange(ref sendAsyncLock, 0);
                                            return true;
                                        }
                                        Interlocked.Exchange(ref sendAsyncLock, 0);
                                        if (--sendDepth == 0)
                                        {
                                            sendDepth = maxSendDepth;
                                            OnSendTask.Task.Add(this);
                                            return true;
                                        }
                                        return onSend();
#endif
                                    }
                                    goto COPY;
                                case ResponseType.SubBuffer:
                                    COPY:
                                    if (buffer.Length - index >= (int)ResponseSize)
                                    {
                                        System.Buffer.BlockCopy(response.Body.Array, state == ResponseState.PartialContent206 ? response.Body.Start + (int)Header.RangeStart : response.Body.Start, buffer.Buffer, buffer.StartIndex + index, (int)ResponseSize);
                                        index += (int)ResponseSize;
                                        ResponseSize = 0;
                                    }
                                    break;
                            }
                        }
                    }
                    if ((socket = Socket) != null)
                    {
                        if (ResponseSize == 0) SendType = SendType.Next;
                        else
                        {
                            this.HttpResponse = response;
                            SendType = SendType.Body;
                            response = null;
                        }
                        Data.Set(buffer.Buffer, buffer.StartIndex, index);
                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                    SocketError socketError;
                    IAsyncResult async = socket.BeginSend(Data.Array, Data.Start, index, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                    if (socketError == SocketError.Success)
                    {
                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                        return true;
                    }
                    return false;
#else
                        while (Interlocked.CompareExchange(ref sendAsyncLock, 1, 0) != 0) Thread.Sleep(0);
                        sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, index);
                        if (socket.SendAsync(sendAsyncEventArgs))
                        {
                            Http.Header.ReceiveTimeout.Push(this, socket);
                            Interlocked.Exchange(ref sendAsyncLock, 0);
                            return true;
                        }
                        Interlocked.Exchange(ref sendAsyncLock, 0);
                        if (--sendDepth == 0)
                        {
                            sendDepth = maxSendDepth;
                            OnSendTask.Task.Add(this);
                            return true;
                        }
                        return onSend();
#endif
                    }
                }
            }
            catch (Exception error)
            {
                Server.RegisterServer.TcpServer.Log.Add(Log.LogType.Error, error);
            }
            finally { Http.Response.Push(ref response); }
            return false;
        }
コード例 #41
0
    public void OnError_Authenticate(int statusCode, int reasonCode, string statusMessage, object cbObject)
    {
        m_state    = ResponseState.Error;
        m_response = reasonCode + ":" + statusMessage;
        Debug.LogError("OnError_Authenticate: " + statusMessage);

        if (ErrorHandling.SharedErrorHandling(statusCode, reasonCode, statusMessage, cbObject, gameObject))
        {
            return;
        }

        switch (reasonCode)
        {
        case ReasonCodes.MISSING_IDENTITY_ERROR:
        {
            // User's identity doesn't match one existing on brainCloud
            // Reset profile id and re-authenticate
            App.Bc.Client.AuthenticationService.ClearSavedProfileID();
            ReAuthenticate(true);

            // @see WrapperAuthenticateDialog for an example that uses
            // permission dialog before creating the new profile

            break;
        }

        case ReasonCodes.SWITCHING_PROFILES:
        {
            // User profile id doesn't match the identity they are attempting to authenticate
            // Reset profile id and re-authenticate
            App.Bc.Client.AuthenticationService.ClearSavedProfileID();
            ReAuthenticate();

            // @see WrapperAuthenticateDialog for an example that uses
            // permission dialog before swapping
            break;
        }

        case ReasonCodes.TOKEN_DOES_NOT_MATCH_USER:
        {
            // User is receiving  an error that they're username or password is wrong.
            // decide how this will be handled, such as prompting the user to re-enter
            // there login details
            Destroy(gameObject);
            ErrorDialog.DisplayErrorDialog(
                "Incorrect username or password. Please check your information and try again.", m_response);

            break;
        }

        case ReasonCodes.MISSING_PROFILE_ERROR:
        {
            // User is receiving an error that they're trying to authenticate an account that doesn't exist.
            // decide how this will be handled, such as creating the account by setting the forceCreate flag to true
            ReAuthenticate(true);

            break;
        }

        default:
        {
            // log the reasonCode to your own internal error checking
            ErrorHandling.UncaughtError(statusCode, reasonCode, statusMessage, cbObject, gameObject);

            break;
        }
        }
    }
コード例 #42
0
 private void ShareResultHandler(ResponseState state, PlatformType type, Hashtable shareInfo, Hashtable error, bool end)
 {
     if (state == ResponseState.Fail)
     {
         int num = 0;
         if (type != PlatformType.WeChatSession && type != PlatformType.WeChatTimeline)
         {
             if (type == PlatformType.YiXinTimeline)
             {
                 num = 4;
             }
         }
         else
         {
             num = 3;
         }
         if (num != 0)
         {
             GameUIManager.mInstance.ShowMessageTip(Singleton<StringManager>.Instance.GetString(string.Format("shareTxt{0}", num)), 0f, 0f);
         }
         this.flagShare = false;
         this.OnCloseSharePopUp();
         return;
     }
     if (state == ResponseState.Success)
     {
         global::Debug.Log(new object[]
         {
             "share result :" + shareInfo
         });
         this.SendAndroidShareAchievement();
         return;
     }
     this.OnCloseSharePopUp();
 }
コード例 #43
0
ファイル: Socket.cs プロジェクト: zhangb12465/AutoCSer
 /// <summary>
 /// 输出错误状态
 /// </summary>
 /// <param name="state">错误状态</param>
 internal override void ResponseErrorIdentity(ResponseState state)
 {
     ++this.Identity;
     ResponseError(state);
 }
コード例 #44
0
 public void CopyFrom(HttpListenerResponse templateResponse) {
     if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, "CopyFrom", "templateResponse#"+ValidationHelper.HashString(templateResponse));
     m_NativeResponse = new UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE();
     m_ResponseState = ResponseState.Created;
     m_WebHeaders = templateResponse.m_WebHeaders;
     m_BoundaryType = templateResponse.m_BoundaryType;
     m_ContentLength = templateResponse.m_ContentLength;
     m_NativeResponse.StatusCode = templateResponse.m_NativeResponse.StatusCode;
     m_NativeResponse.Version.MajorVersion = templateResponse.m_NativeResponse.Version.MajorVersion;
     m_NativeResponse.Version.MinorVersion = templateResponse.m_NativeResponse.Version.MinorVersion;
     m_StatusDescription = templateResponse.m_StatusDescription;
     m_KeepAlive = templateResponse.m_KeepAlive;
 }
コード例 #45
0
 public static void MapExecutionResponse <T>(ExecutionResponse <T> res, Exception ex, string message, ResponseState state)
 {
     res.State     = state;
     res.Exception = ex;
     res.Message   = message;
 }
コード例 #46
0
        public void Close(byte[] responseEntity, bool willBlock) {
            if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Close", " responseEntity="+ValidationHelper.HashString(responseEntity)+" willBlock="+willBlock);
            try {
                CheckDisposed();
                if (responseEntity==null) {
                    throw new ArgumentNullException("responseEntity");
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::Close() ResponseState:" + m_ResponseState + " BoundaryType:" + m_BoundaryType + " ContentLength:" + m_ContentLength);
                if (m_ResponseState<ResponseState.SentHeaders && m_BoundaryType!=BoundaryType.Chunked) {
                    ContentLength64 = responseEntity.Length;
                }
                EnsureResponseStream();
                if (willBlock) {
                    try {
                        m_ResponseStream.Write(responseEntity, 0, responseEntity.Length);
                    }
                    catch (Win32Exception) {
                    }
                    finally {
                        m_ResponseStream.Close();
                        m_ResponseState = ResponseState.Closed;
                        HttpListenerContext.Close();
                    }
                }
                else {
                    // <


                    m_ResponseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
                }
            } finally {
                if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Close", "");
            }
        }
コード例 #47
0
        /*
        12.3
        HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
        The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:

        #define HTTP_SEND_RESPONSE_FLAG_DISCONNECT          0x00000001
        #define HTTP_SEND_RESPONSE_FLAG_MORE_DATA           0x00000002
        #define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER          0x00000004
        #define HTTP_SEND_RESPONSE_FLAG_VALID               0x00000007

        HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
            specifies that the network connection should be disconnected immediately after
            sending the response, overriding the HTTP protocol's persistent connection features.
        HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
            specifies that additional entity body data will be sent by the caller. Thus,
            the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
        HTTP_SEND_RESPONSE_RAW_HEADER:
            specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
            a call to HttpSendHttpResponse() in order to bypass normal header processing. The
            actual HTTP header will be generated by the application and sent as entity body.
            This flag should be passed on the first call to HttpSendResponseEntityBody, and
            not after. Thus, flag is not applicable to HttpSendHttpResponse.
        */
        internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk,
            HttpResponseStreamAsyncResult asyncResult,
            Interop.HttpApi.HTTP_FLAGS flags,
            bool isWebSocketHandshake)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"pDataChunk: { ((IntPtr)pDataChunk)}, asyncResult: {asyncResult}");
            Debug.Assert(!SentHeaders, "SentHeaders is true.");

            if (StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                // User set 401
                // Using the configured Auth schemes, populate the auth challenge headers. This is for scenarios where 
                // Anonymous access is allowed for some resources, but the server later determines that authorization 
                // is required for this request.
                HttpListenerContext.SetAuthenticationHeaders();
            }

            // Log headers
            if (NetEventSource.IsEnabled)
            {
                StringBuilder sb = new StringBuilder("HttpListenerResponse Headers:\n");
                for (int i = 0; i < Headers.Count; i++)
                {
                    sb.Append("\t");
                    sb.Append(Headers.GetKey(i));
                    sb.Append(" : ");
                    sb.Append(Headers.Get(i));
                    sb.Append("\n");
                }
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, sb.ToString());
            }
            _responseState = ResponseState.SentHeaders;
            
            uint statusCode;
            uint bytesSent;
            List<GCHandle> pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake);
            try
            {
                if (pDataChunk != null)
                {
                    _nativeResponse.EntityChunkCount = 1;
                    _nativeResponse.pEntityChunks = pDataChunk;
                }
                else if (asyncResult != null && asyncResult.pDataChunks != null)
                {
                    _nativeResponse.EntityChunkCount = asyncResult.dataChunkCount;
                    _nativeResponse.pEntityChunks = asyncResult.pDataChunks;
                }
                else
                {
                    _nativeResponse.EntityChunkCount = 0;
                    _nativeResponse.pEntityChunks = null;
                }
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpSendHttpResponse flags:" + flags);
                if (StatusDescription.Length > 0)
                {
                    byte[] statusDescriptionBytes = new byte[WebHeaderEncoding.GetByteCount(StatusDescription)];
                    fixed (byte* pStatusDescription = statusDescriptionBytes)
                    {
                        _nativeResponse.ReasonLength = (ushort)statusDescriptionBytes.Length;
                        WebHeaderEncoding.GetBytes(StatusDescription, 0, statusDescriptionBytes.Length, statusDescriptionBytes, 0);
                        _nativeResponse.pReason = (sbyte*)pStatusDescription;
                        fixed (Interop.HttpApi.HTTP_RESPONSE* pResponse = &_nativeResponse)
                        {
                            statusCode =
                                Interop.HttpApi.HttpSendHttpResponse(
                                    HttpListenerContext.RequestQueueHandle,
                                    HttpListenerRequest.RequestId,
                                    (uint)flags,
                                    pResponse,
                                    null,
                                    &bytesSent,
                                    SafeLocalAllocHandle.Zero,
                                    0,
                                    asyncResult == null ? null : asyncResult._pOverlapped,
                                    null);

                            if (asyncResult != null &&
                                statusCode == Interop.HttpApi.ERROR_SUCCESS &&
                                HttpListener.SkipIOCPCallbackOnSuccess)
                            {
                                asyncResult.IOCompleted(statusCode, bytesSent);
                                // IO operation completed synchronously - callback won't be called to signal completion.
                            }
                        }
                    }
                }
                else
                {
                    fixed (Interop.HttpApi.HTTP_RESPONSE* pResponse = &_nativeResponse)
                    {
                        statusCode =
                            Interop.HttpApi.HttpSendHttpResponse(
                                HttpListenerContext.RequestQueueHandle,
                                HttpListenerRequest.RequestId,
                                (uint)flags,
                                pResponse,
                                null,
                                &bytesSent,
                                SafeLocalAllocHandle.Zero,
                                0,
                                asyncResult == null ? null : asyncResult._pOverlapped,
                                null);

                        if (asyncResult != null &&
                            statusCode == Interop.HttpApi.ERROR_SUCCESS &&
                            HttpListener.SkipIOCPCallbackOnSuccess)
                        {
                            asyncResult.IOCompleted(statusCode, bytesSent);
                            // IO operation completed synchronously - callback won't be called to signal completion.
                        }
                    }
                }
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpSendHttpResponse returned:" + statusCode);
            }
            finally
            {
                FreePinnedHeaders(pinnedHeaders);
            }
            return statusCode;
        }
コード例 #48
0
        internal Interop.HttpApi.HTTP_FLAGS ComputeHeaders()
        {
            Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE;
            if (NetEventSource.IsEnabled) NetEventSource.Info(this);
            Debug.Assert(!ComputedHeaders, "ComputedHeaders is true.");
            _responseState = ResponseState.ComputedHeaders;
            
            ComputeCoreHeaders();

            if (NetEventSource.IsEnabled) NetEventSource.Info(this,
                $"flags: {flags} _boundaryType: {_boundaryType} _contentLength: {_contentLength} _keepAlive: {_keepAlive}");
            if (_boundaryType == BoundaryType.None)
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    _keepAlive = false;
                }
                else
                {
                    _boundaryType = BoundaryType.Chunked;
                }
                if (CanSendResponseBody(_httpContext.Response.StatusCode))
                {
                    _contentLength = -1;
                }
                else
                {
                    ContentLength64 = 0;
                }
            }

            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"flags:{flags} _BoundaryType:{_boundaryType} _contentLength:{_contentLength} _keepAlive: {_keepAlive}");
            if (_boundaryType == BoundaryType.ContentLength)
            {
                Headers[HttpResponseHeader.ContentLength] = _contentLength.ToString("D", NumberFormatInfo.InvariantInfo);
                if (_contentLength == 0)
                {
                    flags = Interop.HttpApi.HTTP_FLAGS.NONE;
                }
            }
            else if (_boundaryType == BoundaryType.Chunked)
            {
                Headers[HttpResponseHeader.TransferEncoding] = "chunked";
            }
            else if (_boundaryType == BoundaryType.None)
            {
                flags = Interop.HttpApi.HTTP_FLAGS.NONE; // seems like HTTP_SEND_RESPONSE_FLAG_MORE_DATA but this hangs the app;
            }
            else
            {
                _keepAlive = false;
            }
            if (!_keepAlive)
            {
                Headers.Add(HttpResponseHeader.Connection, "close");
                if (flags == Interop.HttpApi.HTTP_FLAGS.NONE)
                {
                    flags = Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
                }
            }
            else
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    Headers[HttpResponseHeader.KeepAlive] = "true";
                }
            }
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"flags:{flags} _BoundaryType:{_boundaryType} _contentLength:{_contentLength} _keepAlive: {_keepAlive}");
            return flags;
        }
コード例 #49
0
/*
12.3
HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:

#define HTTP_SEND_RESPONSE_FLAG_DISCONNECT          0x00000001
#define HTTP_SEND_RESPONSE_FLAG_MORE_DATA           0x00000002
#define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER          0x00000004
#define HTTP_SEND_RESPONSE_FLAG_VALID               0x00000007

HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
    specifies that the network connection should be disconnected immediately after
    sending the response, overriding the HTTP protocol's persistent connection features.
HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
    specifies that additional entity body data will be sent by the caller. Thus,
    the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
HTTP_SEND_RESPONSE_RAW_HEADER:
    specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
    a call to HttpSendHttpResponse() in order to bypass normal header processing. The
    actual HTTP header will be generated by the application and sent as entity body.
    This flag should be passed on the first call to HttpSendResponseEntityBody, and
    not after. Thus, flag is not applicable to HttpSendHttpResponse.
*/
        internal unsafe uint SendHeaders(UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK* pDataChunk, 
            HttpResponseStreamAsyncResult asyncResult, 
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags,
            bool isWebSocketHandshake) {
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() pDataChunk:" + ValidationHelper.ToString((IntPtr)pDataChunk) + " asyncResult:" + ValidationHelper.ToString(asyncResult));
            GlobalLog.Assert(!SentHeaders, "HttpListenerResponse#{0}::SendHeaders()|SentHeaders is true.", ValidationHelper.HashString(this));
            
            if (StatusCode == (int)HttpStatusCode.Unauthorized) { // User set 401
                // Using the configured Auth schemes, populate the auth challenge headers. This is for scenarios where 
                // Anonymous access is allowed for some resources, but the server later determines that authorization 
                // is required for this request.
                HttpListenerContext.SetAuthenticationHeaders();
            }
            
            // Log headers
            if(Logging.On) {
                StringBuilder sb = new StringBuilder("HttpListenerResponse Headers:\n");
                for (int i=0; i<Headers.Count; i++) {
                    sb.Append("\t");
                    sb.Append(Headers.GetKey(i));
                    sb.Append(" : ");
                    sb.Append(Headers.Get(i));
                    sb.Append("\n");
                }
                Logging.PrintInfo(Logging.HttpListener, this, ".ctor", sb.ToString());
            }
            m_ResponseState = ResponseState.SentHeaders;
            /*
            if (m_BoundaryType==BoundaryType.Raw) {
                use HTTP_SEND_RESPONSE_FLAG_RAW_HEADER;
            }
            */
            uint statusCode;
            uint bytesSent;
            List<GCHandle> pinnedHeaders = SerializeHeaders(ref m_NativeResponse.Headers, isWebSocketHandshake);
            try {
                if (pDataChunk!=null) {
                    m_NativeResponse.EntityChunkCount = 1;
                    m_NativeResponse.pEntityChunks = pDataChunk;
                }
                else if (asyncResult!=null && asyncResult.pDataChunks!=null) {
                    m_NativeResponse.EntityChunkCount = asyncResult.dataChunkCount;
                    m_NativeResponse.pEntityChunks = asyncResult.pDataChunks;
                } 
                else {
                    m_NativeResponse.EntityChunkCount = 0;
                    m_NativeResponse.pEntityChunks = null;
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() calling UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse flags:" + flags);
                if (StatusDescription.Length>0) {
                    byte[] statusDescriptionBytes = new byte[WebHeaderCollection.HeaderEncoding.GetByteCount(StatusDescription)];
                    fixed (byte* pStatusDescription = statusDescriptionBytes) {
                        m_NativeResponse.ReasonLength = (ushort)statusDescriptionBytes.Length;
                        WebHeaderCollection.HeaderEncoding.GetBytes(StatusDescription, 0, statusDescriptionBytes.Length, statusDescriptionBytes, 0);
                        m_NativeResponse.pReason = (sbyte*)pStatusDescription;
                        fixed (UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE* pResponse = &m_NativeResponse) {
                            if (asyncResult != null)
                            {
                                HttpListenerContext.EnsureBoundHandle();
                            }
                            statusCode =
                                UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse(
                                    HttpListenerContext.RequestQueueHandle,
                                    HttpListenerRequest.RequestId,
                                    (uint)flags,
                                    pResponse,
                                    null,
                                    &bytesSent,
                                    SafeLocalFree.Zero,
                                    0,
                                    asyncResult==null ? null : asyncResult.m_pOverlapped,
                                    null );

                            if (asyncResult != null && 
                                statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
                                HttpListener.SkipIOCPCallbackOnSuccess)
                            {
                                asyncResult.IOCompleted(statusCode, bytesSent);
                                // IO operation completed synchronously - callback won't be called to signal completion.
                            }
                        }
                    }
                }
                else {
                    fixed (UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE* pResponse = &m_NativeResponse) {
                        if (asyncResult != null)
                        {
                            HttpListenerContext.EnsureBoundHandle();
                        }
                        statusCode =
                            UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse(
                                HttpListenerContext.RequestQueueHandle,
                                HttpListenerRequest.RequestId,
                                (uint)flags,
                                pResponse,
                                null,
                                &bytesSent,
                                SafeLocalFree.Zero,
                                0,
                                asyncResult==null ? null : asyncResult.m_pOverlapped,
                                null );

                        if (asyncResult != null && 
                            statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
                            HttpListener.SkipIOCPCallbackOnSuccess)
                        {
                            asyncResult.IOCompleted(statusCode, bytesSent);
                            // IO operation completed synchronously - callback won't be called to signal completion.
                        }
                    }
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() call to UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse returned:" + statusCode);
            }
            finally {
                FreePinnedHeaders(pinnedHeaders);
            }
            return statusCode;
        }
コード例 #50
0
        protected void SendResponse(Request request, ResponseState state)
        {
            if (OnResponse != null)
            {
                var respond = new Response(state, request);

                _Logger.WriteToLog("-> Response on incoming call");
                _Logger.WriteToLog(ObjectToLogString.ToLogString(respond));

                OnResponse(this, respond);
            }
        }
コード例 #51
0
        public void Abort() {
            if(Logging.On)Logging.Enter(Logging.HttpListener, this, "abort", "");
            try {
                if (m_ResponseState>=ResponseState.Closed) {
                    return;
                }

                m_ResponseState = ResponseState.Closed;
                HttpListenerContext.Abort();
            } finally {
                if(Logging.On)Logging.Exit(Logging.HttpListener, this, "abort", "");
            }
        }
コード例 #52
0
        /*
         * 12.3
         * HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
         * The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:
         *
         #define HTTP_SEND_RESPONSE_FLAG_DISCONNECT          0x00000001
         #define HTTP_SEND_RESPONSE_FLAG_MORE_DATA           0x00000002
         #define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER          0x00000004
         #define HTTP_SEND_RESPONSE_FLAG_VALID               0x00000007
         *
         * HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
         *  specifies that the network connection should be disconnected immediately after
         *  sending the response, overriding the HTTP protocol's persistent connection features.
         * HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
         *  specifies that additional entity body data will be sent by the caller. Thus,
         *  the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
         * HTTP_SEND_RESPONSE_RAW_HEADER:
         *  specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
         *  a call to HttpSendHttpResponse() in order to bypass normal header processing. The
         *  actual HTTP header will be generated by the application and sent as entity body.
         *  This flag should be passed on the first call to HttpSendResponseEntityBody, and
         *  not after. Thus, flag is not applicable to HttpSendHttpResponse.
         */

        // TODO: Consider using HTTP_SEND_RESPONSE_RAW_HEADER with HttpSendResponseEntityBody instead of calling HttpSendHttpResponse.
        // This will give us more control of the bytes that hit the wire, including encodings, HTTP 1.0, etc..
        // It may also be faster to do this work in managed code and then pass down only one buffer.
        // What would we loose by bypassing HttpSendHttpResponse?
        //
        // TODO: Consider using the HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA flag for most/all responses rather than just Opaque.
        internal unsafe uint SendHeaders(HttpApi.HTTP_DATA_CHUNK[] dataChunks,
                                         ResponseStreamAsyncResult asyncResult,
                                         HttpApi.HTTP_FLAGS flags,
                                         bool isOpaqueUpgrade)
        {
            Debug.Assert(!HasStartedSending, "HttpListenerResponse::SendHeaders()|SentHeaders is true.");

            _responseState = ResponseState.StartedSending;
            var reasonPhrase = GetReasonPhrase(StatusCode);

            /*
             * if (m_BoundaryType==BoundaryType.Raw) {
             *  use HTTP_SEND_RESPONSE_FLAG_RAW_HEADER;
             * }
             */
            uint            statusCode;
            uint            bytesSent;
            List <GCHandle> pinnedHeaders = SerializeHeaders(isOpaqueUpgrade);

            try
            {
                if (dataChunks != null)
                {
                    if (pinnedHeaders == null)
                    {
                        pinnedHeaders = new List <GCHandle>();
                    }
                    var handle = GCHandle.Alloc(dataChunks, GCHandleType.Pinned);
                    pinnedHeaders.Add(handle);
                    _nativeResponse.Response_V1.EntityChunkCount = (ushort)dataChunks.Length;
                    _nativeResponse.Response_V1.pEntityChunks    = (HttpApi.HTTP_DATA_CHUNK *)handle.AddrOfPinnedObject();
                }
                else if (asyncResult != null && asyncResult.DataChunks != null)
                {
                    _nativeResponse.Response_V1.EntityChunkCount = asyncResult.DataChunkCount;
                    _nativeResponse.Response_V1.pEntityChunks    = asyncResult.DataChunks;
                }
                else
                {
                    _nativeResponse.Response_V1.EntityChunkCount = 0;
                    _nativeResponse.Response_V1.pEntityChunks    = null;
                }

                var cachePolicy = new HttpApi.HTTP_CACHE_POLICY();
                var cacheTtl    = CacheTtl;
                if (cacheTtl.HasValue && cacheTtl.Value > TimeSpan.Zero)
                {
                    cachePolicy.Policy        = HttpApi.HTTP_CACHE_POLICY_TYPE.HttpCachePolicyTimeToLive;
                    cachePolicy.SecondsToLive = (uint)Math.Min(cacheTtl.Value.Ticks / TimeSpan.TicksPerSecond, Int32.MaxValue);
                }

                byte[] reasonPhraseBytes = HeaderEncoding.GetBytes(reasonPhrase);
                fixed(byte *pReasonPhrase = reasonPhraseBytes)
                {
                    _nativeResponse.Response_V1.ReasonLength = (ushort)reasonPhraseBytes.Length;
                    _nativeResponse.Response_V1.pReason      = (sbyte *)pReasonPhrase;
                    fixed(HttpApi.HTTP_RESPONSE_V2 *pResponse = &_nativeResponse)
                    {
                        statusCode =
                            HttpApi.HttpSendHttpResponse(
                                RequestContext.RequestQueueHandle,
                                Request.RequestId,
                                (uint)flags,
                                pResponse,
                                &cachePolicy,
                                &bytesSent,
                                SafeLocalFree.Zero,
                                0,
                                asyncResult == null ? SafeNativeOverlapped.Zero : asyncResult.NativeOverlapped,
                                IntPtr.Zero);

                        if (asyncResult != null &&
                            statusCode == ErrorCodes.ERROR_SUCCESS &&
                            WebListener.SkipIOCPCallbackOnSuccess)
                        {
                            asyncResult.BytesSent = bytesSent;
                            // The caller will invoke IOCompleted
                        }
                    }
                }
            }
            finally
            {
                FreePinnedHeaders(pinnedHeaders);
            }
            return(statusCode);
        }
コード例 #53
0
 private void Dispose(bool disposing) {
     if (m_ResponseState>=ResponseState.Closed) {
         return;
     }
     EnsureResponseStream();
     m_ResponseStream.Close();
     m_ResponseState = ResponseState.Closed;
     
     HttpListenerContext.Close();
 }
コード例 #54
0
        internal HttpApi.HTTP_FLAGS ComputeHeaders(bool endOfRequest = false, int bufferedBytes = 0)
        {
            Headers.IsReadOnly = false; // Temporarily allow modification.

            // 401
            if (StatusCode == (ushort)HttpStatusCode.Unauthorized)
            {
                RequestContext.Server.AuthenticationManager.SetAuthenticationChallenge(RequestContext);
            }

            var flags = HttpApi.HTTP_FLAGS.NONE;

            Debug.Assert(!ComputedHeaders, "HttpListenerResponse::ComputeHeaders()|ComputedHeaders is true.");
            _responseState = ResponseState.ComputedHeaders;

            // Gather everything from the request that affects the response:
            var requestVersion          = Request.ProtocolVersion;
            var requestConnectionString = Request.Headers[HttpKnownHeaderNames.Connection];
            var isHeadRequest           = Request.IsHeadMethod;
            var requestCloseSet         = Matches(Constants.Close, requestConnectionString);

            // Gather everything the app may have set on the response:
            // Http.Sys does not allow us to specify the response protocol version, assume this is a HTTP/1.1 response when making decisions.
            var responseConnectionString = Headers[HttpKnownHeaderNames.Connection];
            var transferEncodingString   = Headers[HttpKnownHeaderNames.TransferEncoding];
            var responseContentLength    = ContentLength;
            var responseCloseSet         = Matches(Constants.Close, responseConnectionString);
            var responseChunkedSet       = Matches(Constants.Chunked, transferEncodingString);
            var statusCanHaveBody        = CanSendResponseBody(_requestContext.Response.StatusCode);

            // Determine if the connection will be kept alive or closed.
            var keepConnectionAlive = true;

            if (requestVersion <= Constants.V1_0 || // Http.Sys does not support "Keep-Alive: true" or "Connection: Keep-Alive"
                (requestVersion == Constants.V1_1 && requestCloseSet) ||
                responseCloseSet)
            {
                keepConnectionAlive = false;
            }

            // Determine the body format. If the user asks to do something, let them, otherwise choose a good default for the scenario.
            if (responseContentLength.HasValue)
            {
                _boundaryType = BoundaryType.ContentLength;
                // ComputeLeftToWrite checks for HEAD requests when setting _leftToWrite
                _expectedBodyLength = responseContentLength.Value;
            }
            else if (responseChunkedSet)
            {
                // The application is performing it's own chunking.
                _boundaryType = BoundaryType.PassThrough;
            }
            else if (endOfRequest && !(isHeadRequest && statusCanHaveBody)) // HEAD requests should always end without a body. Assume a GET response would have a body.
            {
                if (bufferedBytes > 0)
                {
                    Headers[HttpKnownHeaderNames.ContentLength] = bufferedBytes.ToString(CultureInfo.InvariantCulture);
                }
                else if (statusCanHaveBody)
                {
                    Headers[HttpKnownHeaderNames.ContentLength] = Constants.Zero;
                }
                _boundaryType       = BoundaryType.ContentLength;
                _expectedBodyLength = bufferedBytes;
            }
            else if (keepConnectionAlive && requestVersion == Constants.V1_1)
            {
                _boundaryType = BoundaryType.Chunked;
                Headers[HttpKnownHeaderNames.TransferEncoding] = Constants.Chunked;
            }
            else
            {
                // The length cannot be determined, so we must close the connection
                keepConnectionAlive = false;
                _boundaryType       = BoundaryType.Close;
            }

            // Managed connection lifetime
            if (!keepConnectionAlive)
            {
                // All Http.Sys responses are v1.1, so use 1.1 response headers
                // Note that if we don't add this header, Http.Sys will often do it for us.
                if (!responseCloseSet)
                {
                    Headers.Append(HttpKnownHeaderNames.Connection, Constants.Close);
                }
                flags = HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
            }

            Headers.IsReadOnly = true; // Prohibit further modifications.
            return(flags);
        }
コード例 #55
0
 private void NonBlockingCloseCallback(IAsyncResult asyncResult) {
     try {
         m_ResponseStream.EndWrite(asyncResult);
     }
     catch (Win32Exception) {
     }
     finally {
         m_ResponseStream.Close();
         HttpListenerContext.Close();
         m_ResponseState = ResponseState.Closed;
     }
 }
コード例 #56
0
 public Response(ResponseState state, Request incomingRequest)
 {
     this.State = state;
     this.IncomingRequest = incomingRequest;
 }
コード例 #57
0
        internal UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS ComputeHeaders() {
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE;
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders()");
            GlobalLog.Assert(!ComputedHeaders, "HttpListenerResponse#{0}::ComputeHeaders()|ComputedHeaders is true.", ValidationHelper.HashString(this));
            m_ResponseState = ResponseState.ComputedHeaders;
            /*
            // here we would check for BoundaryType.Raw, in this case we wouldn't need to do anything
            if (m_BoundaryType==BoundaryType.Raw) {
                return flags;
            }
            */

            ComputeCoreHeaders();

            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders() flags:" + flags + " m_BoundaryType:" + m_BoundaryType + " m_ContentLength:" + m_ContentLength + " m_KeepAlive:" + m_KeepAlive);
            if (m_BoundaryType==BoundaryType.None)
            {
                if (HttpListenerRequest.ProtocolVersion.Minor==0) {
                    // 
                    m_KeepAlive = false;
                }
                else {
                    m_BoundaryType = BoundaryType.Chunked;
                }
                if (CanSendResponseBody(m_HttpContext.Response.StatusCode)) {
                    m_ContentLength = -1;
                }
                else {
                    ContentLength64 = 0;
                }
            }

            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders() flags:" + flags + " m_BoundaryType:" + m_BoundaryType + " m_ContentLength:" + m_ContentLength + " m_KeepAlive:" + m_KeepAlive);
            if (m_BoundaryType==BoundaryType.ContentLength) {
                Headers.SetInternal(HttpResponseHeader.ContentLength, m_ContentLength.ToString("D", NumberFormatInfo.InvariantInfo));
                if (m_ContentLength==0) {
                    flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE;
                }
            }
            else if (m_BoundaryType==BoundaryType.Chunked) {
                Headers.SetInternal(HttpResponseHeader.TransferEncoding, HttpWebRequest.ChunkedHeader);
            }
            else if (m_BoundaryType==BoundaryType.None) {
                flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE; // seems like HTTP_SEND_RESPONSE_FLAG_MORE_DATA but this hangs the app;
            }
            else {
                m_KeepAlive = false;
            }
            if (!m_KeepAlive) {
                Headers.Add(HttpResponseHeader.Connection, "close");
                if (flags==UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE) {
                    flags = UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
                }
            }
            else
            {
                if (HttpListenerRequest.ProtocolVersion.Minor == 0)
                {
                    Headers.SetInternal(HttpResponseHeader.KeepAlive, "true");
                }
            }
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::ComputeHeaders() flags:" + flags + " m_BoundaryType:" + m_BoundaryType + " m_ContentLength:" + m_ContentLength + " m_KeepAlive:" + m_KeepAlive);
            return flags;
        }
コード例 #58
0
 public ApiResponseWrap(ResponseState state, object data) : this(state, data, new Message[0])
 {
 }
コード例 #59
0
 /// <summary>
 /// Creates a new instance of the TcpState class from an exisiting <see cref="ConnectState"/>.
 /// </summary>
 /// <param name="cs">The <see cref="ConnectState"/></param>
 /// <param name="stream">The <see cref="Stream"/> of the connection</param>
 /// <param name="buffer">The buffer to hold the response</param>
 /// <returns><see cref="TcpState"/></returns>
 public static ResponseState FromConnectState(ConnectState cs, Stream stream, byte[] buffer)
 {
     ResponseState state = new ResponseState();
     state.Request = cs.Request;
     state.Stream = stream;
     state.Buffer = buffer;
     return state;
 }
コード例 #60
0
 public ApiResponseWrap(ResponseState state, object data, IEnumerable <Message> messages)
 {
     State    = state;
     Data     = data;
     Messages = messages;
 }