create a http server on a specific port and host in csharp

To create an HTTP server in C#, you can use the HttpListener class from System.Net namespace. Here's an example code snippet that creates an HTTP server on a specific host (localhost) and port (8080):

main.cs
using System;
using System.Net;

class HttpServer
{
    static void Main(string[] args)
    {
        // define the host and port to listen on
        string host = "http://localhost:8080/";
        
        // create an HttpListener to handle incoming requests
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(host);
        
        // start listening for incoming requests
        listener.Start();
        Console.WriteLine($"Server started, listening on {host}...");
        
        while (true)
        {
            // wait for a request to come in
            HttpListenerContext context = listener.GetContext();
            
            // handle the request and send a response
            HttpListenerResponse response = context.Response;
            string responseString = "<html><body>Hello World!</body></html>";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }
}
1155 chars
35 lines

This code creates an HttpListener object that listens for incoming requests on host http://localhost:8080/. It then enters an infinite loop to wait for incoming requests, handles each request as it arrives, and sends a response back to the client.

Note that this code is just a basic example - a real-world HTTP server implementation would need to handle more complex scenarios, such as multiple clients connecting simultaneously, handling different HTTP request types (GET, POST, etc.), and returning different HTTP response codes based on the success or failure of the request.

related categories

gistlibby LogSnag