0

I am trying to create a HTTP/1.1 web server using TcpListener class in C#.

I have created this basic code for receiving incoming connections to the web server.

namespace TCPServer
{
    using System;
    using System.Net;
    using System.Net.Sockets;

    class Program
    {
        private static TcpListener listener;

        private static int count;

        static void Main(string[] args)
        {
            listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, 8080));
            listener.Start();

            BeginAccept();

            while (true)
            {
                Console.ReadLine();
            }
        }

        static void BeginAccept()
        {
            listener.BeginAcceptTcpClient(BeginAcceptCallback, null);
        }

        static void BeginAcceptCallback(IAsyncResult result)
        {
            var id = ++count;
            Console.WriteLine(id + " Connected");

            BeginAccept();
        }
    }
}

But when I run this program and try to connect to http://localhost:8080/ in my web browser (google chrome) I read 3 different connections coming in.

Output:

1 Connected
2 Connected
3 Connected

Only one of these connections contains the prolog and headers of the http request, the other 2 seem to be empty.

Is this standard behavior? If so, what are the other 2 connections used for?

Or is there something I am doing wrong?

Joas
  • 1,796
  • 1
  • 12
  • 25
  • `I am trying to create a HTTP/1.1 web server using TcpListener` if it is not just for learning, use `HttpListener` – Eser Mar 10 '18 at 19:37
  • @Eser This is for learning, I am a student and want to learn more about how HTTP and browsers work. Do you know why the question was marked as duplicate? I still can't figure out why the 2 empty connections are opened.. – Joas Mar 10 '18 at 19:46
  • As mentioned in link, browsers can open *fair* amount of connections to servers to speed up download – Eser Mar 10 '18 at 20:05

0 Answers0