Beispiel #1
0
        /// <summary>
        /// Waits for data to become available for reading on the socket, then reads it into the main buffer for processing
        /// </summary>
        private void ReceiveData(Socket socket, ManualResetEvent abortEvent, ref HttpMessage message, EventHandler <HttpMessageProgressEventArgs> onProgress, object stateObject)
        {
            /*
             * Data Receiving Phase
             * This will receive data from the socket until we have enough data to process.
             * */

            // wait for some bytes to become available
            int bytesAvailable = 0;

            byte[] bytesReceived = new byte[0];

            // if we don't have data left over from last time try and go with just that first
            if (_previouslyReceivedBytes == null)
            {
                // ok there was nothing left over, so we're back to receiving again
                bytesAvailable = HttpUtils.WaitForAvailableBytes(socket, abortEvent);

                // receive as many bytes as we can (a chunk as it were)
                bytesReceived = HttpUtils.ReceiveBytes(socket, bytesAvailable, MAX_BUFFER_LENGTH);
            }

            // if there was anything left over from last time
            if (_previouslyReceivedBytes != null)
            {
                // combine the previous with this chunk
                bytesReceived = HttpUtils.Combine(_previouslyReceivedBytes, bytesReceived);

                Debug.WriteLine(string.Format("Retaining '{0}' bytes from last message.", bytesReceived.Length));

                // reset the previous buffer
                _previouslyReceivedBytes = null;
            }

            // if we have a previous message buffer
            if (_receivedBytes != null)
            {
                // combine what we had, with what we just received
                byte[] buffer = HttpUtils.Combine(_receivedBytes, bytesReceived);
                _receivedBytes = buffer;
            }
            else
            {
                /*
                 * this is the first part of a new message
                 * */
                // otherwise just start with the chunk
                _receivedBytes = bytesReceived;
            }

            // if we have received the headers
            if (this.IsPastHeaders())
            {
                // notify the callback that data has been received
                this.OnProgress(onProgress, this, new HttpMessageProgressEventArgs(message, false, bytesReceived, _receivedBytes.Length, stateObject));
            }
        }