Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9010789
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T02:33:22+00:00 2026-06-16T02:33:22+00:00

I converted a synchronous HTTP Server (using .NET’s HttpListener) to asynchronous following this example

  • 0

I converted a synchronous HTTP Server (using .NET’s HttpListener) to asynchronous following this example. It works, but for every request I issue from Google Chrome, be it hitting enter at the address bar or pressing F5, I get two requests. The first one is perfectly handled, and the response is rendered fine in the browser.

However, the second request, which shouldn’t even appear, has an empty query string (my server is a console application so I see all this happening using Console.WriteLine).

None of this happened when the server was synchronous, so I must have messed something up when moving to the async model.

Here’s the code:

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 );
            }
        }    
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T02:33:24+00:00Added an answer on June 16, 2026 at 2:33 am

    It seems that this happens only when the response is just a bunch of bytes (representing a jpeg image in this case). If instead of entering the http request directly in the address bar I open an HTML page like this…

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

    … one and only one request is received by my server. (I anonymized my port and parameters; where it says queryParametersGoHere, I actually had ?param1=value1&param2=value2, etc.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm developing an Asynchronous Game Server using .Net Socket Asynchronous Model( BeginAccept/EndAccept...etc.) The problem
I am studying the MSDN example code of using asynchronous client-server sockets. I understand
I've converted an api written in Java into a .net dll using IKVM, and
I have a windows service written around some code similar to this Asynchronous Server
I found an example about HTTP POST in msdn, but I am wondering how
I have the following class (I take it from an example on the net,
I'm trying to send an asynchronous http request to the server (django in my
I am creating a simple HTTP client/server application on my local machine but I
I am using the TADOConnection object in Delphi XE but this appears to be
I'm trying to convert a form from synchronous to asynchronous using the Ajax.BeginForm helper

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.