.Net C# simple HttpListener

A simple example of a HttpListener class. Run the program and make a request in your web client.

i.e.

http://localhost:8080/
Then:
http://localhost:8080/go

using System;
using System.Net;

namespace CsharpListenerDemo
{
    static class CsharpListenerExample
    {
        static void Main()
        {
            var web = new HttpListener();

            web.Prefixes.Add("http://localhost:8080/");

            Console.WriteLine("Listening..");

            web.Start();

            Console.WriteLine(web.GetContext());

            var context = web.GetContext();

            var response = context.Response;

            const string responseString = "<html><body>Hello world</body></html>";

            var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;

            var output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);

            Console.WriteLine(output);
            
            output.Close();

            web.Stop();

            Console.ReadKey();
        }
    }
}

Returns:

Hello World

Leave a Reply

Your email address will not be published. Required fields are marked *