/// <summary>
        /// Sends the stream to the remote host.
        /// </summary>
        /// <param name="message">The message.</param>
        public void SendMessage(Message message)
        {
            int            availableConnectionEntry = 0;
            HttpWebRequest httpWebRequest           = null;

            try
            {
                // serialize the message
                GenuineChunkedStream stream = new GenuineChunkedStream(false);
                using (BufferKeeper bufferKeeper = new BufferKeeper(0))
                {
                    MessageCoder.FillInLabelledStream(message, null, null, stream, bufferKeeper.Buffer,
                                                      (int)this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);
                }

                // add the header
                GenuineChunkedStream resultStream = new GenuineChunkedStream(false);
                BinaryWriter         binaryWriter = new BinaryWriter(resultStream);
                HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, GenuineConnectionType.Invocation, this.ITransportContext.BinaryHostIdentifier, HttpPacketType.Usual, message.MessageId, string.Empty, this.Remote.LocalHostUniqueIdentifier);
                if (stream.CanSeek)
                {
                    resultStream.WriteStream(stream);
                }
                else
                {
                    GenuineUtility.CopyStreamToStream(stream, resultStream);
                }

                // get a connection
                availableConnectionEntry = FindAvailableConnectionEntry();
                httpWebRequest           = this.InitializeRequest("__GC_INVC_" + availableConnectionEntry.ToString(), this._keepalive);

                this.InitiateSending(new ConnectionInfo(httpWebRequest, availableConnectionEntry, message), resultStream,
                                     this._httpAsynchronousRequestTimeout);
            }
            catch
            {
                try
                {
                    if (httpWebRequest != null)
                    {
                        httpWebRequest.Abort();
                    }
                }
                catch
                {
                }

                this.ReleaseConnectionEntry(availableConnectionEntry);

                throw;
            }
        }
        /// <summary>
        /// Completes the HTTP request.
        /// </summary>
        /// <param name="ar">The result of the HTTP request.</param>
        private void OnRequestCompleted(IAsyncResult ar)
        {
            HttpWebResponse httpWebResponse = null;
            Stream          inputStream     = null;
            ConnectionInfo  connectionInfo  = null;

            try
            {
                connectionInfo = (ConnectionInfo)ar.AsyncState;
                HttpWebRequest httpWebRequest = connectionInfo.HttpWebRequest;
#if (FRM20)
                // timeout has been already set
                try
                {
                    httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        return;
                    }
                }
#else
                httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(ar);
#endif
                this.Remote.Renew(this._hostRenewingSpan, false);

                // process the content
                inputStream = httpWebResponse.GetResponseStream();

#if DEBUG
//				if (this.ITransportContext.IEventLogger.AcceptBinaryData)
//				{
//					byte[] content = new byte[(int) httpWebResponse.ContentLength];
//					GenuineUtility.ReadDataFromStream(inputStream, content, 0, content.Length);
//
//					this.ITransportContext.IEventLogger.Log(LogMessageCategory.Traffic, null, "HttpInvocationConnection.OnRequestCompleted",
//						content, "The content of the response received by the HttpInvocationConnection. Size: {0}.", content.Length);
//					inputStream = new MemoryStream(content, false);
//				}
#endif

                BinaryReader   binaryReader = new BinaryReader(inputStream);
                string         serverUri;
                int            sequenceNo;
                HttpPacketType httpPacketType;
                int            remoteHostUniqueIdentifier;
                HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier);

#if DEBUG
//				this.ITransportContext.IEventLogger.Log(LogMessageCategory.TransportLayer, null, "HttpInvocationConnection.OnRequestCompleted",
//					null, "The invocation request returned. Server uri: {0}. Sequence no: {1}. Packet type: {2}. Content-encoding: {3}. Content-length: {4}. Protocol version: {5}. Response uri: \"{6}\". Server: \"{7}\". Status code: {8}. Status description: \"{9}\".",
//					serverUri, sequenceNo, Enum.Format(typeof(HttpPacketType), httpPacketType, "g"),
//					httpWebResponse.ContentEncoding, httpWebResponse.ContentLength,
//					httpWebResponse.ProtocolVersion, httpWebResponse.ResponseUri,
//					httpWebResponse.Server, httpWebResponse.StatusCode, httpWebResponse.StatusDescription);
#endif

                // if the remote host has asked to terminate a connection
                if (httpPacketType == HttpPacketType.ClosedManually || httpPacketType == HttpPacketType.Desynchronization || httpPacketType == HttpPacketType.SenderError)
                {
                    throw GenuineExceptions.Get_Receive_ConnectionClosed();
                }

                // skip the first byte
                if (binaryReader.ReadByte() != 0)
                {
                    if (!connectionInfo.Message.IsOneWay)
                    {
//						this.ITransportContext.IEventLogger.Log(LogMessageCategory.FatalError, GenuineExceptions.Get_Processing_LogicError("The invocation response doesn't contain any messages."), "HttpInvocationConnection.OnRequestCompleted",
//							null, "The HTTP response doesn't contain content. The response to the request was not received.");
                    }
                }
                else
                {
                    // fetch and process the response messages
                    using (BufferKeeper bufferKeeper = new BufferKeeper(0))
                    {
                        using (LabelledStream labelledStream = new LabelledStream(this.ITransportContext, inputStream, bufferKeeper.Buffer))
                        {
                            GenuineChunkedStream receivedRequest = new GenuineChunkedStream(true);
                            GenuineUtility.CopyStreamToStream(labelledStream, receivedRequest);
                            this.ITransportContext.IIncomingStreamHandler.HandleMessage(receivedRequest, this.Remote, GenuineConnectionType.Invocation, string.Empty, -1, true, null, null, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
//				this.ITransportContext.IEventLogger.Log(LogMessageCategory.Error, ex, "HttpInvocationConnection.OnRequestCompleted",
//					null, "Exception occurred during receiving a response to an invocation request.");

                // dispatch the exception to the caller context
                if (connectionInfo != null)
                {
                    this.ITransportContext.IIncomingStreamHandler.DispatchException(connectionInfo.Message, ex);
                }
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Close();
                }
                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }

                // release the connection
                if (connectionInfo != null)
                {
                    this.ReleaseConnectionEntry(connectionInfo.Index);
                }
            }
        }