create a http server with a connect route in csharp

Here is an example code to create a basic HTTP server with a Connect style route in C#:

main.cs
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Http_Server
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();
            Console.WriteLine("Listening...");

            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                string message = "Hello World!";

                //Set the message based on the request path
                if (context.Request.Url.AbsolutePath == "/hello")
                {
                    message = "Hello!";
                }
                else if (context.Request.Url.AbsolutePath == "/world")
                {
                    message = "World!";
                }

                byte[] buffer = Encoding.UTF8.GetBytes(message);

                context.Response.ContentLength64 = buffer.Length;
                Stream output = context.Response.OutputStream;

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

                output.Close();
                context.Response.Close();
            }
        }
    }
}
1229 chars
45 lines

In this example, we are creating a HTTPListener object to listen to requests on the URL "http://localhost:8080/". We then loop indefinitely, waiting for incoming requests. When a request arrives, we check its URL path to determine which message to return. Finally, we construct a response with the message, write it to the response stream, and close the output and response streams.

gistlibby LogSnag