/// <summary>
        /// Operates with failed sockets.
        /// </summary>
        /// <param name="exception">The source exception.</param>
        /// <param name="xHttpConnection">The failed logical connection.</param>
        /// <param name="xHttpPhysicalConnection">The failed physical connection.</param>
        private void ConnectionFailed(Exception exception, XHttpConnection xHttpConnection, XHttpPhysicalConnection xHttpPhysicalConnection)
        {
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;

            try
            {
                if (xHttpPhysicalConnection == null && xHttpConnection == null)
                {
                    // LOG:
                    if ( binaryLogWriter != null )
                    {
                        binaryLogWriter.WriteImplementationWarningEvent("XHttpConnectionManager.ConnectionFailed",
                            LogMessageType.ConnectionFailed, exception,
                            GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                            "The connection has not been specified while invoking XHttpConnectionManager.ConnectionFailed.");
                    }
                    return ;
                }

                OperationException operationException = exception as OperationException;
                bool conflict409Received = false;
                if (operationException != null)
                    conflict409Received = operationException.OperationErrorMessage.ErrorIdentifier.IndexOf("ConflictOfConnections") >= 0;

                // if it's a server, just close the connection
                // if it's a client sender, re-send it again
                // if it's a client listener, re-send the request again with the same seq no
                bool tryToReestablish = ! ConnectionManager.IsExceptionCritical(exception as OperationException);

                HostInformation remote = null;
                if (xHttpConnection != null)
                    remote = xHttpConnection.Remote;

                // LOG:
                if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
                {
                    binaryLogWriter.WriteEvent(LogCategory.Connection, "XHttpConnectionManager.ConnectionFailed",
                        LogMessageType.ConnectionFailed, exception, null, remote, null,
                        GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                        null, null,
                        xHttpConnection == null ? -1 : xHttpConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
                        "XHTTP connection has failed.");
                }

                using (new ReaderAutoLocker(this._disposeLock))
                {
                    if (this._disposed)
                        tryToReestablish = false;
                }

                // close the socket
                if (xHttpPhysicalConnection != null)
                    GenuineThreadPool.QueueUserWorkItem(new WaitCallback(SocketUtility.CloseSocket), xHttpPhysicalConnection.Socket, true);

                switch (xHttpConnection.GenuineConnectionType)
                {
                    case GenuineConnectionType.Persistent:
                        // ignore connections causing conflict
                        if (conflict409Received)
                            break;

                        lock (remote.PersistentConnectionEstablishingLock)
                        {
                            using (new ReaderAutoLocker(this._disposeLock))
                            {
                                if (! tryToReestablish || xHttpConnection.IsDisposed)
                                {
                                    this._persistent.Remove(remote.PrimaryUri, xHttpConnection.ConnectionName);

                                    // release all resources
                                    this.ITransportContext.KnownHosts.ReleaseHostResources(xHttpConnection.Remote, exception);
                                    xHttpConnection.Dispose(exception);

                                    xHttpConnection.SignalState(GenuineEventType.GeneralConnectionClosed, exception, null);
                                    if (exception is OperationException && ((OperationException) exception).OperationErrorMessage.ErrorIdentifier == "GenuineChannels.Exception.Receive.ServerHasBeenRestarted")
                                        xHttpConnection.SignalState(GenuineEventType.GeneralServerRestartDetected, exception, null);
                                    break;
                                }

                                xHttpConnection.SignalState(GenuineEventType.GeneralConnectionReestablishing, exception, null);

                                // start reestablishing
                                if (remote.GenuinePersistentConnectionState == GenuinePersistentConnectionState.Opened)
                                {
                                    // start the reestablishing, if possible
                                    if (xHttpPhysicalConnection != null && xHttpPhysicalConnection.Reestablish_ObtainStatus())
                                        GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.ReestablishConnection), xHttpPhysicalConnection, true);
                                }

                            }	// using (new ReaderAutoLocker(this._disposeLock))
                        }	// lock (remote.PersistentConnectionEstablishingLock)
                        break;

                    case GenuineConnectionType.Invocation:
                        break;
                }
            }
            catch(Exception ex)
            {
                // LOG:
                if ( binaryLogWriter != null )
                    binaryLogWriter.WriteImplementationWarningEvent("XHttpConnectionManager.ConnectionFailed",
                        LogMessageType.Warning, ex, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                        "An unexpected exception is raised inside XHttpConnectionManager.ConnectionFailed method. Most likely, something must be fixed.");
            }
        }
        /// <summary>
        /// Initiates sending through the physical asynchronously.
        /// </summary>
        /// <param name="xHttpPhysicalConnection">The physical connection.</param>
        /// <returns>True if the sending was initiated. False if the specified physical connection contains no data to send.</returns>
        private bool LowLevel_InitiateAsyncSending(XHttpPhysicalConnection xHttpPhysicalConnection)
        {
            // initiate the sending
            xHttpPhysicalConnection.AsyncSendBufferCurrentPosition = 0;
            xHttpPhysicalConnection.AsyncSendBufferSizeOfValidContent = GenuineUtility.TryToReadFromStream(xHttpPhysicalConnection.AsyncSendStream, xHttpPhysicalConnection.AsyncSendBuffer, 0, xHttpPhysicalConnection.AsyncSendBuffer.Length);
            if (xHttpPhysicalConnection.AsyncSendBufferSizeOfValidContent == 0)
                return false;
            xHttpPhysicalConnection.AsyncSendBufferIsLastPacket = xHttpPhysicalConnection.AsyncSendBufferSizeOfValidContent < xHttpPhysicalConnection.AsyncSendBuffer.Length;

            // LOG:
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
            if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
                binaryLogWriter.WriteEvent(LogCategory.Transport, "XHttpConnectionManager.LowLevel_InitiateAsyncSending",
                    LogMessageType.AsynchronousSendingStarted, null, null, xHttpPhysicalConnection.Remote, null,
                    GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                    null, null,
                    xHttpPhysicalConnection.XHttpConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
                    "The connection has been obtained and the stream is being sent asynchronously.");

            AsyncThreadStarter.QueueTask(new Async_InitiateSocketSending(xHttpPhysicalConnection.Socket, xHttpPhysicalConnection.AsyncSendBuffer,
                xHttpPhysicalConnection.AsyncSendBufferCurrentPosition,
                xHttpPhysicalConnection.AsyncSendBufferSizeOfValidContent - xHttpPhysicalConnection.AsyncSendBufferCurrentPosition,
                this._AsyncSending_onEndSending, xHttpPhysicalConnection));

            return true;
        }
 /// <summary>
 /// Constructs an instance of the PhysicalConnectionAndSocket class.
 /// </summary>
 /// <param name="xHttpPhysicalConnection">The connection.</param>
 /// <param name="socket">The socket.</param>
 public PhysicalConnectionAndSocket(XHttpPhysicalConnection xHttpPhysicalConnection, Socket socket)
 {
     this.Socket = socket;
     this.XHttpPhysicalConnection = xHttpPhysicalConnection;
 }
        /// <summary>
        /// Initiates receiving of the message's header.
        /// </summary>
        /// <param name="xHttpPhysicalConnection">The physical connection.</param>
        internal void LowLevel_HalfSync_Client_StartReceiving(XHttpPhysicalConnection xHttpPhysicalConnection)
        {
            // LOG:
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
            if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
            {
                binaryLogWriter.WriteEvent(LogCategory.Transport, "XHttpConnectionManager.LowLevel_HalfSync_Client_StartReceiving",
                    LogMessageType.ReceivingStarted, null, null, xHttpPhysicalConnection.Remote, null,
                    GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                    xHttpPhysicalConnection.ConnectionLevelSecurity,
                    xHttpPhysicalConnection.ConnectionLevelSecurity == null ? null : xHttpPhysicalConnection.ConnectionLevelSecurity.Name,
                    xHttpPhysicalConnection.XHttpConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
                    "The asynchronous receiving is initiated.");
            }

            // check the connection
            xHttpPhysicalConnection.CheckConnectionStatus();

            // and initiate receiving
            AsyncThreadStarter.QueueTask(new Async_InitiateSocketReceiving(xHttpPhysicalConnection.Socket,
                this._unusedBuffer, 0,
                1,
                _HalfSync_Client_onEndReceiving, xHttpPhysicalConnection));
        }
        /// <summary>
        /// Processes the listening request on the server side.
        /// </summary>
        /// <param name="xHttpConnection">The connection.</param>
        /// <param name="xHttpPhysicalConnection">The physical connection.</param>
        private void Pool_Server_ProcessListenerRequest(XHttpConnection xHttpConnection, XHttpPhysicalConnection xHttpPhysicalConnection)
        {
            lock (xHttpConnection.Listener.PhysicalConnectionStateLock)
            {
                try
                {
                    Message message = xHttpConnection.MessageContainer.GetMessage();
                    if (message == null)
                    {
                        // no data is available, postpone the request
            //						xHttpPhysicalConnection.Listener_Opened = GenuineUtility.TickCount;
                        xHttpPhysicalConnection.MarkAsAvailable();
                        return;
                    }

                    // some data is available, gather the stream and send it
                    this.LowLevel_SendHttpContent(GenuineUtility.GetTimeout(xHttpConnection.CloseConnectionAfterInactivity),
                        message, null, null, xHttpConnection.MessageContainer, xHttpPhysicalConnection,
                        xHttpConnection.GenuineConnectionType, HttpPacketType.Usual,
                        false, true, true, true);
                }
                catch(Exception ex)
                {
                    // LOG:
                    BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
                    if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
                    {
                        binaryLogWriter.WriteEvent(LogCategory.Connection, "XHttpConnectionManager.Pool_Server_ProcessListenerRequest",
                            LogMessageType.AsynchronousSendingStarted, ex,
                            null, xHttpPhysicalConnection.Remote, null,
                            GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                            null, null,
                            xHttpConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
                            "Error occurred while sending HTTP Listener Request. Sequence No: {0}.",
                            xHttpPhysicalConnection.SequenceNo);
                    }
                }
            }
        }
        /// <summary>
        /// Processes the sending request on the server side.
        /// </summary>
        /// <param name="xHttpConnection">The connection.</param>
        /// <param name="xHttpPhysicalConnection">The physical connection.</param>
        /// <param name="inputStream">The connection.</param>
        private void Pool_Server_ProcessSenderRequest(XHttpConnection xHttpConnection, XHttpPhysicalConnection xHttpPhysicalConnection, Stream inputStream)
        {
            Exception gotException = null;

            try
            {
                this.LowLevel_ParseLabelledStream(inputStream, xHttpPhysicalConnection);
                inputStream.Close();
            }
            catch(Exception ex)
            {
                gotException = ex;

                // LOG:
                BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
                if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
                {
                    binaryLogWriter.WriteEvent(LogCategory.Connection, "XHttpConnectionManager.Pool_Server_ProcessSenderRequest",
                        LogMessageType.ReceivingFinished, ex,
                        null, xHttpConnection.Remote, null,
                        GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                        null, null,
                        xHttpConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
                        "Error occurred while parsing HTTP Sender Request. Sequence No: {0}.",
                        xHttpPhysicalConnection.SequenceNo);
                }
            }

            if (gotException != null)
            {
                gotException = OperationException.WrapException(gotException);
                GenuineChunkedStream outputStream = new GenuineChunkedStream(false);
                BinaryFormatter binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other));
                binaryFormatter.Serialize(outputStream, gotException);

                this.LowLevel_SendHttpContent(GenuineUtility.GetTimeout(xHttpConnection.CloseConnectionAfterInactivity),
                    null, null, gotException, null, xHttpPhysicalConnection,
                    GenuineConnectionType.Persistent, HttpPacketType.SenderError,
                    false, true, true, false);
            }
            else
            {
                // serialize and send the OK response
                this.LowLevel_SendHttpContent(GenuineUtility.GetTimeout(xHttpConnection.CloseConnectionAfterInactivity),
                    null, null, null, null, xHttpPhysicalConnection, GenuineConnectionType.Persistent,
                    HttpPacketType.SenderResponse, false, true, true, false);
            }
        }
        /// <summary>
        /// Starts sending a message if one is available. Marks the connection is available if there are no messages at the moment.
        /// Does not process exceptions.
        /// </summary>
        /// <param name="xHttpPhysicalConnection">The sending connection.</param>
        private void Pool_Sender_HandleClientConnection(XHttpPhysicalConnection xHttpPhysicalConnection)
        {
            lock (xHttpPhysicalConnection.PhysicalConnectionStateLock)
            {
                Message message = xHttpPhysicalConnection.XHttpConnection.MessageContainer.GetMessage();
                if (message == null)
                {
                    xHttpPhysicalConnection.MarkAsAvailable();
                    return ;
                }

                this.LowLevel_SendHttpContent(GenuineUtility.GetTimeout(xHttpPhysicalConnection.XHttpConnection.CloseConnectionAfterInactivity),
                    message, null, null, xHttpPhysicalConnection.XHttpConnection.MessageContainer,
                    xHttpPhysicalConnection, GenuineConnectionType.Persistent, HttpPacketType.Usual,
                    false, true, true, true);
            }
        }
 /// <summary>
 /// Starts sending a message if one is available. Marks the connection is available if there are no messages at the moment.
 /// Does not process exceptions.
 /// </summary>
 /// <param name="xHttpPhysicalConnection">The sending connection.</param>
 private void Pool_Listener_HandleClientConnection(XHttpPhysicalConnection xHttpPhysicalConnection)
 {
     this.LowLevel_SendHttpContent(GenuineUtility.GetTimeout(xHttpPhysicalConnection.XHttpConnection.CloseConnectionAfterInactivity),
         null, null, null, null, xHttpPhysicalConnection, GenuineConnectionType.Persistent,
         HttpPacketType.Listening, false, true, true, true);
 }
 /// <summary>
 /// Sends a request to the server according to the type of the connection provided.
 /// Does not process exceptions.
 /// </summary>
 /// <param name="xHttpPhysicalConnection"></param>
 private void Pool_HandleClientConnection(XHttpPhysicalConnection xHttpPhysicalConnection)
 {
     // client & sender - start sending a message or mark the connection as available
     // client & listener - send the next request
     if (xHttpPhysicalConnection.IsSender)
         Pool_Sender_HandleClientConnection(xHttpPhysicalConnection);
     else
         Pool_Listener_HandleClientConnection(xHttpPhysicalConnection);
 }
        /// <summary>
        /// Sends HTTP content to the remote host.
        /// Does not process exceptions.
        /// Automatically initiates asynchronous receiving.
        /// Automatically manages stream seqNo for clients' connections.
        /// </summary>
        /// <param name="timeout">Operation timeout.</param>
        /// <param name="message">The message.</param>
        /// <param name="content">The content sent instead of the message.</param>
        /// <param name="exceptionToBeSent">The exception being sent in the response.</param>
        /// <param name="messageContainer">The message container.</param>
        /// <param name="xHttpPhysicalConnection">The physical connection.</param>
        /// <param name="genuineConnectionType">The type of the connection.</param>
        /// <param name="httpPacketType">The type of the HTTP packet.</param>
        /// <param name="repeatSending">Whether the content was already packed.</param>
        /// <param name="synchronous">Whether to send content synchronously.</param>
        /// <param name="startAutomaticReceiving">Indicates whether to start automatic receiving of the response/request if the type of the sending is synchronous.</param>
        /// <param name="applyClss">A boolean value indicating whether the CLSS should be applied.</param>
        private void LowLevel_SendHttpContent(int timeout, Message message, 
            GenuineChunkedStream content, Exception exceptionToBeSent,
            MessageContainer messageContainer, XHttpPhysicalConnection xHttpPhysicalConnection,
            GenuineConnectionType genuineConnectionType, HttpPacketType httpPacketType,
            bool repeatSending, bool synchronous, bool startAutomaticReceiving, bool applyClss
            )
        {
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;

            // check whether the connection is valid and available
            xHttpPhysicalConnection.CheckConnectionStatus();

            // prevent the ping
            if (! xHttpPhysicalConnection.IsSender)
                xHttpPhysicalConnection.XHttpConnection.LastTimeContentWasSent = GenuineUtility.TickCount;

            // valid copies
            Socket socket;
            Stream sentContent;

            // to prevent from changing sequence information or disposing sent content during its encryption
            lock (xHttpPhysicalConnection.PhysicalConnectionStateLock)
            {
                if (! repeatSending)
                {
                    if (xHttpPhysicalConnection.XHttpConnection.IsClient)
                        xHttpPhysicalConnection.SequenceNo ++;

                    if (message != null || (message == null && content == null && exceptionToBeSent == null))
                    {
                        GenuineChunkedStream packedMessages = new GenuineChunkedStream(false);
                        MessageCoder.FillInLabelledStream(message, messageContainer,
                            xHttpPhysicalConnection.MessagesBeingSent, packedMessages,
                            xHttpPhysicalConnection.AsyncSendBuffer,
                            (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);

                        // LOG:
                        if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 )
                        {
                            for ( int i = 0; i < xHttpPhysicalConnection.MessagesBeingSent.Count; i++)
                            {
                                Message nextMessage = (Message) xHttpPhysicalConnection.MessagesBeingSent[i];

                                binaryLogWriter.WriteEvent(LogCategory.Transport, "XHttpConnectionManager.LowLevel_SendHttpContent",
                                    LogMessageType.MessageIsSentAsynchronously, null, nextMessage, xHttpPhysicalConnection.Remote, null,
                                    GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, xHttpPhysicalConnection.ConnectionLevelSecurity, null,
                                    xHttpPhysicalConnection.XHttpConnection.DbgConnectionId, xHttpPhysicalConnection.SequenceNo, 0, 0, null, null, null, null,
                                    "The message will be sent in the {0} stream N: {1}.",
                                    xHttpPhysicalConnection == xHttpPhysicalConnection.XHttpConnection.Sender ? "SENDER" : "LISTENER",
                                    xHttpPhysicalConnection.SequenceNo);
                            }
                        }

                        xHttpPhysicalConnection.SentContent = packedMessages;
                    }
                    else if (content != null)
                    {
                        xHttpPhysicalConnection.MessagesBeingSent.Clear();
                        xHttpPhysicalConnection.SentContent = content;
                    }
                    else //if (exceptionToBeSent != null)
                    {
            #if DEBUG
                        Debug.Assert(httpPacketType == HttpPacketType.SenderError);
            #endif

                        Exception exception = OperationException.WrapException(exceptionToBeSent);
                        GenuineChunkedStream output = new GenuineChunkedStream(false);
                        BinaryFormatter binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other));
                        binaryFormatter.Serialize(output, exception);

                        xHttpPhysicalConnection.MessagesBeingSent.Clear();
                        xHttpPhysicalConnection.SentContent = output;
                    }

                    // client applies CLSSE only to the actual content
                    if (applyClss && xHttpPhysicalConnection.XHttpConnection.IsClient && xHttpPhysicalConnection.ConnectionLevelSecurity != null)
                    {
                        GenuineChunkedStream encryptedContent = new GenuineChunkedStream(false);
                        xHttpPhysicalConnection.ConnectionLevelSecurity.Encrypt(xHttpPhysicalConnection.SentContent, encryptedContent);
                        xHttpPhysicalConnection.SentContent = encryptedContent;
                    }

                    // write the binary header
                    GenuineChunkedStream resultStream = new GenuineChunkedStream(false);
                    BinaryWriter binaryWriter = new BinaryWriter(resultStream);

                    if (xHttpPhysicalConnection.XHttpConnection.IsClient)
                        HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, genuineConnectionType, xHttpPhysicalConnection.XHttpConnection.HostId, httpPacketType, xHttpPhysicalConnection.SequenceNo, xHttpPhysicalConnection.XHttpConnection.ConnectionName, xHttpPhysicalConnection.XHttpConnection.Remote.LocalHostUniqueIdentifier);
                    else
                        HttpMessageCoder.WriteResponseHeader(binaryWriter, xHttpPhysicalConnection.XHttpConnection.Remote.ProtocolVersion, this.ITransportContext.ConnectionManager.Local.Uri, xHttpPhysicalConnection.SequenceNo, httpPacketType, xHttpPhysicalConnection.XHttpConnection.Remote.LocalHostUniqueIdentifier);

                    resultStream.WriteStream(xHttpPhysicalConnection.SentContent);
                    xHttpPhysicalConnection.SentContent = resultStream;

                    // while server applies CLSSE to the entire response (except HTTP stuff, of course)
                    if (applyClss && ! xHttpPhysicalConnection.XHttpConnection.IsClient && xHttpPhysicalConnection.ConnectionLevelSecurity != null)
                    {
                        GenuineChunkedStream encryptedContent = new GenuineChunkedStream(false);
                        xHttpPhysicalConnection.ConnectionLevelSecurity.Encrypt(xHttpPhysicalConnection.SentContent, encryptedContent);
                        xHttpPhysicalConnection.SentContent = encryptedContent;
                    }

                    // generally it's impossible to have xHttpPhysicalConnection.SentContent without available length in the current implementation
                    // nevertheless, it's necessary to calculate the final length of the content if it's unknown
                    if (! xHttpPhysicalConnection.SentContent.CanSeek)
                    {
                        GenuineChunkedStream actualContent = new GenuineChunkedStream(false);
                        GenuineUtility.CopyStreamToStream(xHttpPhysicalConnection.SentContent, actualContent, xHttpPhysicalConnection.AsyncSendBuffer);
                        xHttpPhysicalConnection.SentContent = actualContent;
                    }

                    // write the header and compose final content
                    resultStream = new GenuineChunkedStream(false);
                    StreamWriter streamWriter = new StreamWriter(new NonClosableStream(resultStream), Encoding.ASCII, 3500);

                    if (xHttpPhysicalConnection.XHttpConnection.IsClient)
                        streamWriter.Write("POST /{0} HTTP/1.1\r\nAccept: */*\r\nContent-Type: application/octet-stream\r\nContent-Length: {1}\r\nUser-Agent: {2}\r\nHost: {3}\r\nConnection: Keep-Alive\r\nPragma: no-cache\r\n\r\n",
                            xHttpPhysicalConnection.EntryUri, xHttpPhysicalConnection.SentContent.Length, xHttpPhysicalConnection.XHttpConnection.UserAgent, xHttpPhysicalConnection.LocalEndPoint);
                    else
                    {
                        string now = DateTime.Now.ToString("r");
                        streamWriter.Write("HTTP/1.1 200 OK\r\nServer: GXHTTP\r\nDate: {0}\r\nX-Powered-By: Genuine Channels\r\nCache-Control: private\r\nContent-Type: application/octet-stream\r\nContent-Length: {1}\r\n\r\n",
                            now, xHttpPhysicalConnection.SentContent.Length);
                    }

                    streamWriter.Flush();
                    streamWriter.Close();
                    resultStream.WriteStream(xHttpPhysicalConnection.SentContent);

                    xHttpPhysicalConnection.SentContent = resultStream;
                }
                else
                {
                    xHttpPhysicalConnection.SentContent.Position = 0;
                }

                socket = xHttpPhysicalConnection.Socket;
                sentContent = xHttpPhysicalConnection.SentContent;
            }	// lock (xHttpPhysicalConnection.PhysicalConnectionStateLock)

            if (synchronous)
            {
                // send the content
                SyncSocketWritingStream syncSocketWritingStream = new SyncSocketWritingStream(this, socket, timeout, xHttpPhysicalConnection.XHttpConnection.DbgConnectionId, xHttpPhysicalConnection.Remote);
                GenuineUtility.CopyStreamToStreamPhysically(sentContent, syncSocketWritingStream, xHttpPhysicalConnection.AsyncSendBuffer);

                // automatically start receiving the response/request
                if (startAutomaticReceiving)
                {
                    if (xHttpPhysicalConnection.XHttpConnection.IsClient)
                        this.LowLevel_HalfSync_Client_StartReceiving(xHttpPhysicalConnection);
                    else
                        this.LowLevel_HalfSync_Server_StartReceiving(xHttpPhysicalConnection.Socket);
                }
            }
            else
            {
                xHttpPhysicalConnection.AsyncSendBufferCurrentPosition = 0;
                xHttpPhysicalConnection.AsyncSendBufferIsLastPacket = false;
                xHttpPhysicalConnection.AsyncSendBufferSizeOfValidContent = 0;
                xHttpPhysicalConnection.AsyncSendStream = sentContent;

                this.LowLevel_InitiateAsyncSending(xHttpPhysicalConnection);
            }
        }
        /// <summary>
        /// Reads messages from the stream and processes them.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="xHttpPhysicalConnection">The connection.</param>
        private void LowLevel_ParseLabelledStream(Stream stream, XHttpPhysicalConnection xHttpPhysicalConnection)
        {
            BinaryReader binaryReader = new BinaryReader(stream);

            while ( binaryReader.ReadByte() == 0 )
            {
                using (LabelledStream labelledStream = new LabelledStream(this.ITransportContext, stream, xHttpPhysicalConnection.AsyncReceiveBuffer))
                {
                    GenuineChunkedStream receivedContent = new GenuineChunkedStream(true);
                    GenuineUtility.CopyStreamToStream(labelledStream, receivedContent);
                    this.ITransportContext.IIncomingStreamHandler.HandleMessage(receivedContent, xHttpPhysicalConnection.Remote, xHttpPhysicalConnection.XHttpConnection.GenuineConnectionType, xHttpPhysicalConnection.XHttpConnection.ConnectionName, xHttpPhysicalConnection.XHttpConnection.DbgConnectionId, false, null, xHttpPhysicalConnection.ConnectionLevelSecurity, null);
                }
            }
        }