Jean Hibbert's Blog

.NET Framework, SQL Server and other random thoughts.

Write your own web server in less than 40 lines

I've recently been toying with the System.Net.Sockets namespace... and this is how easy it is to write your own web server:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;

using System.Net.Sockets;

using System.Threading;

 

namespace MyFirstWebServer

{

    class Program

    {

        static void Main(string[] args)

        {

            TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8010);

            listener.Start();

            TcpClient client = listener.AcceptTcpClient();

            NetworkStream networkStream = client.GetStream();

            StreamReader reader = new StreamReader(networkStream);

            StreamWriter writer = new StreamWriter(networkStream);

            String line = reader.ReadLine();

            while (line != null && line.Length > 0)

            {

                Console.WriteLine(line);

                line = reader.ReadLine();

            }

            writer.WriteLine("<html><head><title>Hello World!</title></head><body>Hello World!</body></html>");

            writer.Flush();

            networkStream.Close();

            reader.Close();

            writer.Close();

            while (true)

            {

                Thread.Sleep(1000);

            }

        }

    }

}

The TCPListener accepts a pending connection request, writes out the request header to the console and returns the HTML string containing the "hello world".

The header output from the browser request:

 

The HTML string sent back to the browser:

 

Easy peasy lemon squeezy.