繁体   English   中英

异步HTTP Server收到虚假请求

[英]Async HTTP Server receiving spurious request

此示例之后,我将同步HTTP服务器(使用.NET的HttpListener)转换为异步。 它可以工作,但是对于我从Google Chrome浏览器发出的每个请求,无论是在地址栏上按Enter还是按F5键,我都会收到两个请求。 第一个被完美地处理,并且响应在浏览器中呈现良好。

但是,第二个请求(甚至不应该出现)都具有一个空查询字符串(我的服务器是控制台应用程序,因此我使用Console.WriteLine看到了所有这些情况)。

当服务器处于同步状态时,这一切都没有发生,因此在移至异步模型时,我一定搞砸了。

这是代码:

using System;
using System.Diagnostics;
using System.Net;

namespace MyWebServer{

    internal static class MyHTTPServer {
        private static int mPortNumber = 7091;
        private static HttpListener mListener;
        private static MyCustomHttpHandler mHttpHandler;

        //Omitted some auxiliary methods to print stuff to Console,
        //like WriteError and WriteRequestHeaderInformation

        public static void Main( String[] pArg ) {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
            HttpHandler = new MyCustomHttpHandler();
            mPortNumber = Convert.ToInt32( pArg[0] );
            Console.WriteLine( "Starting the HttpListener on port:{0}", mPortNumber );
            InitialiseListener();
            Console.WriteLine( "Listener started on port: {0}, waiting for requests.", mPortNumber );
            Console.WriteLine( "Listening. Press Enter to stop." );
            Console.ReadLine();
            if( mListener.IsListening )
                mListener.Stop();
        }

        private static void InitialiseListener() {
            try {
                mListener = new HttpListener {
                    AuthenticationSchemes = AuthenticationSchemes.Basic
                };
                string prefix = string.Format( "http://+:{0}/", mPortNumber );
                mListener.Prefixes.Add( prefix );
                mListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                mListener.Start();
                mListener.BeginGetContext( RequestReceived, null );
            } catch( Exception ex ) {
                WriteError( ex.Message );
            }
        }

        private static void RequestReceived( IAsyncResult result ) {
            var timer = new Stopwatch();
            Console.WriteLine( "---Request Received----" );
            timer.Reset();
            timer.Start();
            //Retrieve context; on error, print message and wait for another request
            HttpListenerContext context = null;
            try {
                context = mListener.EndGetContext( result );
            } catch( HttpListenerException e ) {
                WriteError( e.ToString() );
                if( mListener.IsListening )
                    mListener.BeginGetContext( RequestReceived, null );
                return;
            }
            //Process request and send response
            mListener.BeginGetContext( RequestReceived, null );
            try {
                WriteRequestHeaderInformation( context );
                CreateResponseDocument( context );
            } catch( Exception ex ) {
                WriteError( ex.Message );
            }
            Console.WriteLine( "----Request processed in {0} milliseconds ----", timer.ElapsedMilliseconds );
        }

        private static void CreateResponseDocument( HttpListenerContext pHttpListenerContext ) {
            try {
                byte[] htmlOutput = HttpHandler.ProcessRequest( pHttpListenerContext.Request.Url.LocalPath.Replace( "/", "" ), pHttpListenerContext.Request.Url.Query.Replace( "?", "" ) );
                if( htmlOutput != null && pHttpListenerContext.Response.OutputStream.CanWrite ) {
                    pHttpListenerContext.Response.Headers.Add( "Access-Control-Allow-Origin", "*" );
                    //pHttpListenerContext.Response.ContentType = "image/jpg";
                    pHttpListenerContext.Response.ContentType = "text/plain";
                    pHttpListenerContext.Response.OutputStream.Write( htmlOutput, 0, htmlOutput.Length );
                }
                pHttpListenerContext.Response.Close();
            } catch( Exception ex ) {
                WriteError( ex.Message );
            }
        }    
    }
}

似乎只有在响应只是一堆字节时才会发生这种情况(在这种情况下代表jpeg图像)。 如果不是直接在地址栏中输入http请求,而是打开这样的HTML页面...

 <html>
     <head/>
        <body>
            <img src="http://localhost:serverPort/queryParametersGoHere" />
        </body>
</html>

...我的服务器仅收到一个请求。 (我对端口和参数进行了匿名处理;在上面显示为queryParametersGoHere,实际上我有?param1=value1&param2=value2 ,等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM