0

我按照这个示例将同步 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 );
            }
        }    
    }
}
4

1 回答 1

0

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

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

...我的服务器收到一个且只有一个请求。(我匿名了我的端口和参数;它说 queryParametersGoHere,我实际上有?param1=value1&param2=value2,等等。

于 2012-12-19T14:13:02.427 回答