private void ClientConnected( AdkSocketConnection connection )
 {
     IPEndPoint point = (IPEndPoint) connection.Socket.RemoteEndPoint;
     Console.WriteLine
         ( "Client Connected: {0}:{1}. Total Connections:{2}", point.Address, point.Port,
           connection.Binding.ConnectionCount );
 }
示例#2
0
        private void ClientConnected(AdkSocketConnection connection)
        {
            IPEndPoint point = (IPEndPoint)connection.Socket.RemoteEndPoint;

            Console.WriteLine
                ("Client Connected: {0}:{1}. Total Connections:{2}", point.Address, point.Port,
                connection.Binding.ConnectionCount);
        }
        public static void ProcessRequest( AdkSocketConnection socket,
                                           AdkHttpListener listener )
        {
            AdkHttpRequestContext context = socket.UserData as AdkHttpRequestContext;
            if ( context == null ) {
                AdkHttpConnection conn = new AdkHttpConnection( socket, listener );
                AdkHttpResponse response = new AdkHttpResponse( conn );
                AdkHttpRequest request = new AdkHttpRequest( conn );
                context = listener.Server.CreateContext( conn, request, response );
            }

            context.Connection.ProcessRequest( context, socket );
        }
        public static void ProcessRequest(AdkSocketConnection socket,
                                          AdkHttpListener listener)
        {
            AdkHttpRequestContext context = socket.UserData as AdkHttpRequestContext;

            if (context == null)
            {
                AdkHttpConnection conn     = new AdkHttpConnection(socket, listener);
                AdkHttpResponse   response = new AdkHttpResponse(conn);
                AdkHttpRequest    request  = new AdkHttpRequest(conn);
                context = listener.Server.CreateContext(conn, request, response);
            }

            context.Connection.ProcessRequest(context, socket);
        }
示例#5
0
        public void Receive(AdkSocketConnection connection)
        {
            if (fContentLength == -1)
            {
                MemoryStream initialBuffer =
                    new MemoryStream
                        (connection.RawBuffer, 0, connection.RawBufferLength, false, false);
                AdkHttpHeadersReader reader = new AdkHttpHeadersReader(initialBuffer);
                ParseRequestLine(reader);
                ParseHeaders(reader);
                // This server does not support transfer encoding
                if (this.Headers["Transfer-Encoding"] != null)
                {
                    throw new AdkHttpException
                              (AdkHttpStatusCode.ServerError_501_Not_Implemented,
                              "'Transfer-Encoding' is not supported");
                }


                IPEndPoint endPoint = (IPEndPoint)connection.Socket.LocalEndPoint;
                string     host     = fHeaders["Host"];
                if (host == null)
                {
                    host = endPoint.Address.ToString();
                }
                else
                {
                    int loc = host.IndexOf(':');
                    if (loc > 0)
                    {
                        host = host.Substring(0, loc);
                    }
                }
                // TODO: Implement better parsing of the query string. This will sometimes blow up when it shouldn't.
                string []  pathAndQuery = this.Path.Split('?');
                UriBuilder builder      =
                    new UriBuilder
                        ("http", host, connection.Binding.Port, pathAndQuery[0],
                        pathAndQuery.Length > 1 ? pathAndQuery[1] : "");
                fUri = new Uri(builder.ToString());

                // Now create the request stream, but chop of the headers
                if (this.ContentLength > 0)
                {
                    fRequestStream = new MemoryStream((int)this.ContentLength);
                    fRequestStream.Write
                        (connection.RawBuffer, (int)reader.Position,
                        (int)(connection.RawBufferLength - reader.Position));
                }
            }
            else if (ReceiveComplete)
            {
                throw new AdkHttpException
                          (AdkHttpStatusCode.ClientError_400_Bad_Request,
                          "Too much data received for specified Content-Length");
            }
            else
            {
                fRequestStream.Write(connection.RawBuffer, 0, connection.RawBufferLength);
            }
        }
示例#6
0
 private void Error(AdkSocketConnection connection,
                    Exception ex)
 {
     Console.WriteLine("ERROR: {0}:{1}", ex.Message, ex.StackTrace);
 }
示例#7
0
 private void ClientDisconnected(AdkSocketConnection connection)
 {
     Console.WriteLine
         ("Client Disconnected: Total Connections:{0}", connection.Binding.ConnectionCount);
 }
示例#8
0
 protected void HandleSocketMessage(AdkSocketConnection socketConnection)
 {
     AdkHttpConnection.ProcessRequest(socketConnection, this);
 }
示例#9
0
        public void Receive( AdkSocketConnection connection )
        {
            if ( fContentLength == -1 ) {
                MemoryStream initialBuffer =
                    new MemoryStream
                        ( connection.RawBuffer, 0, connection.RawBufferLength, false, false );
                AdkHttpHeadersReader reader = new AdkHttpHeadersReader( initialBuffer );
                ParseRequestLine( reader );
                ParseHeaders( reader );
                // This server does not support transfer encoding
                if ( this.Headers["Transfer-Encoding"] != null ) {
                    throw new AdkHttpException
                        ( AdkHttpStatusCode.ServerError_501_Not_Implemented,
                          "'Transfer-Encoding' is not supported" );
                }

                IPEndPoint endPoint = (IPEndPoint) connection.Socket.LocalEndPoint;
                string host = fHeaders["Host"];
                if ( host == null ) {
                    host = endPoint.Address.ToString();
                }
                else {
                    int loc = host.IndexOf( ':' );
                    if ( loc > 0 ) {
                        host = host.Substring( 0, loc );
                    }
                }
                // TODO: Implement better parsing of the query string. This will sometimes blow up when it shouldn't.
                string [] pathAndQuery = this.Path.Split( '?' );
                UriBuilder builder =
                    new UriBuilder
                        ( "http", host, connection.Binding.Port, pathAndQuery[0],
                          pathAndQuery.Length > 1 ? pathAndQuery[1] : "" );
                fUri = new Uri( builder.ToString() );

                // Now create the request stream, but chop of the headers
                if ( this.ContentLength > 0 ) {
                    fRequestStream = new MemoryStream( (int) this.ContentLength );
                    fRequestStream.Write
                        ( connection.RawBuffer, (int) reader.Position,
                          (int) (connection.RawBufferLength - reader.Position) );
                }
            }
            else if ( ReceiveComplete ) {
                throw new AdkHttpException
                    ( AdkHttpStatusCode.ClientError_400_Bad_Request,
                      "Too much data received for specified Content-Length" );
            }
            else {
                fRequestStream.Write( connection.RawBuffer, 0, connection.RawBufferLength );
            }
        }
 private void ClientDisconnected( AdkSocketConnection connection )
 {
     Console.WriteLine
         ( "Client Disconnected: Total Connections:{0}", connection.Binding.ConnectionCount );
 }
        private void ProcessRequest( AdkHttpRequestContext context,
                                     AdkSocketConnection socket )
        {
            int aStart = Environment.TickCount;

            bool keepAlive = true;
            AdkHttpRequest request = context.Request;
            AdkHttpResponse response = context.Response;
            try {
                context.Request.Receive( socket );
                if ( !context.Request.ReceiveComplete ) {
                    socket.UserData = context;
                    return;
                }
                else {
                    IAdkHttpHandler handler = fListener.GetHandlerForContext( request );
                    handler.ProcessRequest( context );
                }
            }

            catch ( AdkHttpException httpEx ) {
                _logError( httpEx );
                response.Clear();
                response.Status = httpEx.HttpExceptionCode;
                if ( (int) httpEx.HttpExceptionCode > 499 ) {
                    keepAlive = false;
                }
                response.AdditionalInfo = httpEx.GetType().FullName + " - " + httpEx.Message + " - " +
                                          httpEx.StackTrace;
            }
            catch ( Exception ex ) {
                keepAlive = false;
                _logError( ex );
                // TODO : Implement more verbose error output ( internalexceptions and such )
                response.Clear();
                response.Status = AdkHttpStatusCode.ServerError_500_Internal_Server_Error;
                response.AdditionalInfo = ex.GetType().FullName + " - " + ex.Message + " - " +
                                          ex.StackTrace;
            }

            // Clear out the context state because we are done with this request and the socket
            // may remain open for the next request
            socket.UserData = null;

            if ( socket.Connected ) {
                if ( keepAlive ) {
                    keepAlive = ShouldKeepAlive( context.Request );
                }
                context.Response.Headers.Add( "X-Powered-By", fListener.Server.Name );
                // Write the Response
                context.Response.AsyncFinishRequest( socket, context.Request, keepAlive );

                if ( (Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0 &&
                     fListener.Server.Log.IsDebugEnabled ) {
                    fListener.Server.Log.Info
                        ( string.Format
                              ( "Processed Request for {0}:{1} ( {2} ) in {3} milliseconds",
                                this.ClientEndPoint.Address, this.ClientEndPoint.Port,
                                context.Request.Path, (Environment.TickCount - aStart).ToString() ) );
                }
                if ( !keepAlive ) {
                    socket.Close();
                }
            }
        }
 private AdkHttpConnection( AdkSocketConnection socket,
                            AdkHttpListener listener )
 {
     fSocketConnection = socket;
     fListener = listener;
 }
示例#13
0
        private void ProcessRequest(AdkHttpRequestContext context,
                                    AdkSocketConnection socket)
        {
            int aStart = Environment.TickCount;

            bool            keepAlive = true;
            AdkHttpRequest  request   = context.Request;
            AdkHttpResponse response  = context.Response;

            try {
                context.Request.Receive(socket);
                if (!context.Request.ReceiveComplete)
                {
                    socket.UserData = context;
                    return;
                }
                else
                {
                    IAdkHttpHandler handler = fListener.GetHandlerForContext(request);
                    handler.ProcessRequest(context);
                }
            }

            catch (AdkHttpException httpEx) {
                _logError(httpEx);
                response.Clear();
                response.Status = httpEx.HttpExceptionCode;
                if ((int)httpEx.HttpExceptionCode > 499)
                {
                    keepAlive = false;
                }
                response.AdditionalInfo = httpEx.GetType().FullName + " - " + httpEx.Message + " - " +
                                          httpEx.StackTrace;
            }
            catch (Exception ex) {
                keepAlive = false;
                _logError(ex);
                // TODO : Implement more verbose error output ( internalexceptions and such )
                response.Clear();
                response.Status         = AdkHttpStatusCode.ServerError_500_Internal_Server_Error;
                response.AdditionalInfo = ex.GetType().FullName + " - " + ex.Message + " - " +
                                          ex.StackTrace;
            }

            // Clear out the context state because we are done with this request and the socket
            // may remain open for the next request
            socket.UserData = null;

            if (socket.Connected)
            {
                if (keepAlive)
                {
                    keepAlive = ShouldKeepAlive(context.Request);
                }
                context.Response.Headers.Add("X-Powered-By", fListener.Server.Name);
                // Write the Response
                context.Response.AsyncFinishRequest(socket, context.Request, keepAlive);

                if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0 &&
                    fListener.Server.Log.IsDebugEnabled)
                {
                    fListener.Server.Log.Info
                        (string.Format
                            ("Processed Request for {0}:{1} ( {2} ) in {3} milliseconds",
                            this.ClientEndPoint.Address, this.ClientEndPoint.Port,
                            context.Request.Path, (Environment.TickCount - aStart).ToString()));
                }
                if (!keepAlive)
                {
                    socket.Close();
                }
            }
        }
示例#14
0
 private AdkHttpConnection(AdkSocketConnection socket,
                           AdkHttpListener listener)
 {
     fSocketConnection = socket;
     fListener         = listener;
 }
示例#15
0
        /// <summary>
        /// Copies the response buffer to the outgoing socket using an efficient asynchronous pattern.
        /// </summary>
        /// <param name="socket">The socket to write the result to</param>
        /// <param name="request">The source request</param>
        /// <param name="finishHandler">The delegate to call when the asynchronous operation is complete</param>
        /// <param name="asyncState">The state that should be returned to the async delegate</param>
        internal void AsyncFinishRequest( AdkSocketConnection socket,
                                          AdkHttpRequest request,
                                          bool keepAlive )
        {
            string statusDescription = ParseDescription( fStatus );

            if ( this.Status != AdkHttpStatusCode.Success_200_OK ) {
                this.Clear();
                if ( ShouldReturnBody( this.Status ) ) {
                    this.Write( "<html><head><title>" );
                    this.Write( statusDescription );
                    this.Write( "</title></head><body><h1>HTTP " );
                    this.Write( ((int) fStatus).ToString() );
                    this.Write( " " );
                    this.Write( statusDescription );
                    this.Write( "</h1><br>" );
                    this.Write( this.AdditionalInfo );
                    this.Write( "</body></html>" );
                }
            }

            // Flush our underlying stream. We are done writing to the response and we need the correct length
            this.Flush();
            Stream outputStream = socket.GetOutputDataStream();
            StreamWriter aWriter = new StreamWriter( outputStream );
            {
                aWriter.Write( request.Protocol );
                aWriter.Write( " " );
                aWriter.Write( (int) fStatus );
                aWriter.Write( " " );
                aWriter.Write( statusDescription );
                aWriter.Write( "\r\n" );
                aWriter.Write( "Content-Length: " + fResponseStream.Length.ToString() + "\r\n" );

                if ( keepAlive ) {
                    aWriter.Write( "Connection: Keep-Alive\r\n" );
                }
                else {
                    aWriter.Write( "Connection: Close\r\n" );
                }

                foreach ( string aKey in fHeaders.Keys ) {
                    aWriter.WriteLine( "{0}: {1}", aKey, fHeaders[aKey] );
                }

                aWriter.Write( string.Empty + "\r\n" );
                aWriter.Flush();
                GC.SuppressFinalize( aWriter );
            }
            if ( socket.Connected && fResponseStream.Length > 0 ) {
                fWriter.Flush();
                GC.SuppressFinalize( fWriter );
                fResponseStream.Seek( 0, SeekOrigin.Begin );
                Streams.CopyStream( fResponseStream, outputStream, 4096 );
            }
        }
 private void Error( AdkSocketConnection connection,
                     Exception ex )
 {
     Console.WriteLine( "ERROR: {0}:{1}", ex.Message, ex.StackTrace );
 }
示例#17
0
        /// <summary>
        /// Copies the response buffer to the outgoing socket using an efficient asynchronous pattern.
        /// </summary>
        /// <param name="socket">The socket to write the result to</param>
        /// <param name="request">The source request</param>
        /// <param name="finishHandler">The delegate to call when the asynchronous operation is complete</param>
        /// <param name="asyncState">The state that should be returned to the async delegate</param>
        internal void AsyncFinishRequest(AdkSocketConnection socket,
                                         AdkHttpRequest request,
                                         bool keepAlive)
        {
            string statusDescription = ParseDescription(fStatus);

            if (this.Status != AdkHttpStatusCode.Success_200_OK)
            {
                this.Clear();
                if (ShouldReturnBody(this.Status))
                {
                    this.Write("<html><head><title>");
                    this.Write(statusDescription);
                    this.Write("</title></head><body><h1>HTTP ");
                    this.Write(((int)fStatus).ToString());
                    this.Write(" ");
                    this.Write(statusDescription);
                    this.Write("</h1><br>");
                    this.Write(this.AdditionalInfo);
                    this.Write("</body></html>");
                }
            }

            // Flush our underlying stream. We are done writing to the response and we need the correct length
            this.Flush();
            Stream       outputStream = socket.GetOutputDataStream();
            StreamWriter aWriter      = new StreamWriter(outputStream);

            {
                aWriter.Write(request.Protocol);
                aWriter.Write(" ");
                aWriter.Write((int)fStatus);
                aWriter.Write(" ");
                aWriter.Write(statusDescription);
                aWriter.Write("\r\n");
                aWriter.Write("Content-Length: " + fResponseStream.Length.ToString() + "\r\n");

                if (keepAlive)
                {
                    aWriter.Write("Connection: Keep-Alive\r\n");
                }
                else
                {
                    aWriter.Write("Connection: Close\r\n");
                }

                foreach (string aKey in fHeaders.Keys)
                {
                    aWriter.WriteLine("{0}: {1}", aKey, fHeaders[aKey]);
                }

                aWriter.Write(string.Empty + "\r\n");
                aWriter.Flush();
                GC.SuppressFinalize(aWriter);
            }
            if (socket.Connected && fResponseStream.Length > 0)
            {
                fWriter.Flush();
                GC.SuppressFinalize(fWriter);
                fResponseStream.Seek(0, SeekOrigin.Begin);
                Streams.CopyStream(fResponseStream, outputStream, 4096);
            }
        }
示例#18
0
 protected void HandleSocketMessage( AdkSocketConnection socketConnection )
 {
     AdkHttpConnection.ProcessRequest( socketConnection, this );
 }