Breaking News
Home / .NET / CSharp / CSharp Snippets / Building a Simple Web Server using C#.NET

Building a Simple Web Server using C#.NET

Visual Studio .Net framework provides you enough resources to write your own web server. Of course a web server for real life usage should be very robust and sophisticated. But first we’ll see how we can get around creating the most fundamental web server using C#.Net. This article explains the step by step process of writing a console application for a basic web server.

.NET framework 2.0 and above provides the HTTPListener class, which allows you to a specific port for incoming http requests. We use that to create our simple multi-threaded web server.

Above is the sample C# code for the web server. The code implements methods for continuously listening to incoming requests and process them.

public class WebServer
{
    private static System.Threading.AutoResetEvent listenForNextRequest = new System.Threading.AutoResetEvent(false);

    protected WebServer()
    {
        httpListener = new HttpListener();
    }

    private HttpListener httpListener;

    public string Prefix { get; set; }
    public void Start()
    {
        if (String.IsNullOrEmpty(Prefix))
            throw new InvalidOperationException("Specify prefix");
        httpListener.Prefixes.Clear();
        httpListener.Prefixes.Add(Prefix);
        httpListener.Start();
        System.Threading.ThreadPool.QueueUserWorkItem(Listen);
    }

    internal void Stop()
    {
        httpListener.Stop();
        IsRunning = false;
    }

    public bool IsRunning { get; private set; }

    // Loop here to begin processing of new requests. 
    private void Listen(object state)
    {
        while (httpListener.IsListening)
        {
            httpListener.BeginGetContext(new AsyncCallback(ListenerCallback), httpListener);
            listenForNextRequest.WaitOne();
        }
    }
}

 [pb_builder]

Leave a Reply