Building a Simple HTTP Server in C# with HttpListener

Building a Simple HTTP Server in C# with HttpListener
In this article [Show more]

    Building a Simple HTTP Server in C# with HttpListener

    Setting up an HTTP server might seem hard, but it’s actually quite simple. With the HttpListener class in C#, you can build a basic server and learn how web servers work. In this guide, I’ll show you how to set one up, write code to handle requests, and explain the key parts..

    What is HttpListener?

     HttpListener is a class in the System.Net namespace. It lets you create a simple HTTP server. You can listen for requests at a specific URL and send responses. It’s great for testing, handling custom requests, or creating lightweight servers.

    Getting Started

     

     First, create a new C# console application. This will be the base for your server. If you’re using .NET 8 or later, you can set it up quickly with these commands:

    dotnet new console -n SimpleHttpServer
    cd SimpleHttpServer

    That’s it. Now let’s write the code.

    Writing the Server Code

    Here’s the code for a simple server. It listens for HTTP requests, processes them, and sends a response. The code uses top-level statements, so it’s clean and easy to follow:

    using System;
    using System.Net;
    using System.Threading.Tasks;
    
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:5111/");  
    listener.Start();
    Console.WriteLine("Listening on http://localhost:5111/");
    while (true)
    {
        HttpListenerContext context = await listener.GetContextAsync();
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;
        // Process the request
        string responseString = @"
            <html>
                <body>
                    <h1>Hello, world!</h1>
                    <p>This is a simple HTTP server implemented in C#.</p>
                    <p>Visit us at: <a href='https://dotnetteach.com'>dotnetteach.com</a></p>
                </body>
            </html>";
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        response.ContentLength64 = buffer.Length;
        using (var output = response.OutputStream)
        {
            await output.WriteAsync(buffer, 0, buffer.Length);
        }
        response.Close();
    }

    Output:

    How to create HTTP server in C#

    How It Works

    Here’s a simple explanation of what the code does:

    Create the Listener
    The HttpListener listens for HTTP requests. In this example, it listens on http://localhost:5111/.

    Start Listening
    The Start method begins accepting requests.

    Handle Requests
    In a loop, the server waits for requests using GetContextAsync(). When a request comes in, it’s processed, and a response is prepared.

    Send Responses
    The response is a simple HTML page. It’s written to the response stream and sent to the client.

     

    Testing Your Server

     Run the application. Then, open a browser or use a tool like curl to visit the server:

    curl http://localhost:5111/

    You’ll see a “Hello, world!” message along with some extra information about the server. Try it out it’s satisfying to see it work.

    Conclusion

    That’s it! You’ve built a basic HTTP server in C#. This setup is great for learning and testing. From here, you can add more features, like handling different requests, serving files, or connecting it to other tools. The possibilities are endless. Have fun experimenting!

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments