Category Archives: Web Server

A Minimal Http Server in C#

Two months ago, I wrote a post implementing a Java minimal HTTP Server:

A Minimal Http Server in Java

These days, I began to explore node.js. I want to implements a minimal server in AjSharp that maps incoming request to dynamic functions, a la node.js/Javascript. But before that, I wanted a pure C# minimal implementation. I could use TcpListener (like the java ServerSocket I used in the previous post) as in the project (2001):

Create your own Web Server using C#

But in .NET, we have a minimal web listener in the class System.Net.HttpListener. See:

HttpListener for dummies: a simple “HTTP Request” reflector

So, I wrote the minimal console code:

class Program
{
    static string rootDirectory;
    static void Main(string[] args)
    {
        rootDirectory = args[0];
        HttpListener listener = new HttpListener();
        for (int k = 1; k < args.Length; k++)
            listener.Prefixes.Add(args[k]);
        listener.Start();
        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            Process(context);
        }
    }
    private static void Process(HttpListenerContext context)
    {
        string filename = context.Request.Url.AbsolutePath;
        Console.WriteLine(filename);
        filename = filename.Substring(1);
        if (string.IsNullOrEmpty(filename))
            filename = "index.html";
        filename = Path.Combine(rootDirectory, filename);
        Stream input = new FileStream(filename, FileMode.Open);
        byte[] buffer = new byte[1024*16];
        int nbytes;
        while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
            context.Response.OutputStream.Write(buffer, 0, nbytes);
        input.Close();
        context.Response.OutputStream.Close();
    }
}

The web server return the content of static files, from a root directory. The first parameter is the root directory, and the rest of parameters are the patterns to listen:

The result, using the static files I have in my Tomcat doc directory:

The output at console:

Next steps: use this code in AjSharp. Or extend it to support a pool of threads, or extend it to support /run/<commmandtoexecute> in the server.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez