2

I cannot find any documentation about how the HttpListener handles KeepAlive.

When looking at HttpListenerRequest from the HttpListenercontext I don't see any "GetRequest" methods, but only a RequestStream.

Is it save to assume that HttpListener handles KeepAlive under the hood and creates a new Context each time? If it does reuse the Context, how do I handle multiple request exactly?

I tried a simple but complete example using internet explorer (keep-alive is in the request). This creates a new context each time, but I'm not sure if this is because I'm disposing the stream.

using System.IO;
using System.Net;

namespace Sandbox
{
    public class Program
    {
        private static void Main()
        {
            var listener = new HttpListener();

            // might need to execute elevated cmd: netsh add urlacl url=http://localhost:6302/ user=DOMAIN\user listen=yes
            listener.Prefixes.Add("http://localhost:6302/");

            listener.Start();
            var count = 0;
            while (true)
            {
                var context = listener.GetContext();
                try
                {
                    // Is this dispose the reason i get a new context each time?
                    using (var writer = new StreamWriter(context.Response.OutputStream))
                        writer.Write("Hello World! {0}", ++count);
                }
                finally
                {
                    // context.Response.Close();
                }
            }
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CSharpie
  • 9,195
  • 4
  • 44
  • 71
  • 1
    AFAIK HttpListener is based on http.sys which underlies IIS. It surely supports Keep-Alive. If it didn't it would be the worlds worst HTTP server. Context != Connection. – usr Feb 26 '16 at 13:48
  • 1
    Indeed it reuses the connection and creates a new Context for each request, it's fully transparent for the user, I'm using it on production servers an that's the behavior it has. – Gusman Feb 26 '16 at 13:56
  • Ok i will assume it then. – CSharpie Feb 26 '16 at 14:03
  • You could check with Wireshark. Run an infinite loop making requests. In Wireshark you should see zero TCP syn packets very quickly. – usr Feb 26 '16 at 14:35
  • Here is an anweser from JohnSkeet regarding the matter http://stackoverflow.com/a/4933493/1789202. Its about the request but this probably isnt too far away. – CSharpie Feb 26 '16 at 14:47
  • That's for outgoing requests. That infrastructure shares nothing with the one for incoming requests. – usr Feb 26 '16 at 14:48

0 Answers0