Angel \”Java\” Lopez on Blog

February 1, 2011

A Minimal Http Server in C#

Filed under: .NET, C Sharp, Web Server — ajlopez @ 10:02 am

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

7 Comments »

  1. [...] This post was mentioned on Twitter by ajlopez and Pedro Wood, Malassezio Furfur. Malassezio Furfur said: RT @ajlopez: Daily post: A Minimal Http Server in C# (English) http://bit.ly/dNXfpy [...]

    Pingback by Tweets that mention A Minimal Http Server in C# « Angel “Java” Lopez on Blog -- Topsy.com — February 1, 2011 @ 1:23 pm

  2. [...] A Minimal Http Server In C# [...]

    Pingback by PythonSharp (1) A minimal Web Server « Angel ”Java” Lopez on Blog — December 7, 2012 @ 4:52 pm

  3. [...] A Minimal Http Server In C# [...]

    Pingback by PythonSharp (1) Un servidor web mínimo - Angel "Java" Lopez — December 8, 2012 @ 2:38 pm

  4. […] here […]

    Pingback by Blog J.Schweiss | Minimal HTTP-Server — June 15, 2013 @ 12:37 pm

  5. This is a fantastic web page, thanks with this. I needed for you to the search engines designed
    for a lot of several hours to uncover that location.
    I loathe as soon as each and every time I actually search engines
    intended for article content to read through My partner and i in most cases find incomprehensible articles or blog posts plus lots of spammy.

    An individual plainly consider care and attention of every one of the unsolicited mail along with conserve your
    web site thoroughly clean plus good quality.
    Don’t you have got suggestions pertaining to mine website?

    Comment by Marta — July 14, 2013 @ 1:15 pm

  6. You have to consider though how a material of choice for many contractors due to its
    roofing 101 online education durability, low cost and the cooling
    cost can be radically decreased. As a responsible homeowner, you need to consider all the different kinds of material for the roofing and the
    upgrade. One of the benefits of metal roofing, the entire
    roof.

    Comment by Sherman — September 5, 2013 @ 10:34 pm

  7. If you are really worried about walking your dog in the dark, why not invest
    in a dog lead coupler and torch. Another idea is to use reflectors to bounce some light into shadow areas
    of the photograph. Concentrating Linear Fresnel Reflectors are CSP-plants which use many thin mirror strips instead of parabolic mirrors to
    concentrate sunlight onto two tubes with working fluid.

    Comment by Download .NET Reflector 8.3 Activator — August 8, 2014 @ 7:55 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Theme: Shocking Blue Green. Get a free blog at WordPress.com

Follow

Get every new post delivered to your Inbox.

Join 67 other followers

%d bloggers like this: