create a http server on a specific port in csharp

To create an HTTP server on a specific port in C#, you can use the HttpListener class from the System.Net namespace. Here is an example:

main.cs
using System;
using System.Net;

class Program 
{
    static void Main(string[] args)
    {
        try
        {
            // Define a port number
            int port = 8080;

            // Create a HttpListener object
            HttpListener listener = new HttpListener();

            // Add the prefix for the URL (http://localhost:8080/)
            listener.Prefixes.Add(string.Format("http://localhost:{0}/", port));

            // Start listening for incoming requests
            listener.Start();

            Console.WriteLine("Server running at http://localhost:{0}/", port);

            // Process incoming requests
            while (true)
            {
                HttpListenerContext context = listener.GetContext(); // Wait for a request
                HttpListenerRequest request = context.Request;

                // Get the response object
                HttpListenerResponse response = context.Response;

                // Set the content type and length headers
                response.ContentType = "text/plain";
                response.ContentLength64 = 13;

                // Write the response body
                using (System.IO.Stream output = response.OutputStream)
                {
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Hello, World!");
                    output.Write(buffer, 0, buffer.Length);
                }

                // Close the response
                response.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: {0}", ex.Message);
        }
    }
}
1611 chars
54 lines

In this example, we first define a port number (8080) and create an HttpListener object. We then add the URL prefix for the server (http://localhost:8080/) and start listening for incoming requests.

We use an infinite loop to continuously wait for incoming requests and process them by writing a "Hello, World!" response to the client.

Note: this example does not handle exceptions or errors. In a production server, you would need to handle errors gracefully and close the HttpListener object before exiting the program.

related categories

gistlibby LogSnag