setup webserver in csharp

To set up a web server in C#, you can use the HttpListener class that comes with the .NET Framework. This class allows you to listen for incoming HTTP requests and respond to them.

Here is a basic example of setting up a web server using HttpListener:

main.cs
using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/"); // Set up the URL for the server

        listener.Start(); // Start the server

        Console.WriteLine("Listening...");

        while (true)
        {
            var context = listener.GetContext(); // Wait for a request

            var response = context.Response;
            var responseString = "<html><body><h1>Hello World!</h1></body></html>";
            var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            var output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length); // Send the response
            output.Close();
        }
    }
}
847 chars
30 lines

In this example, we are setting up the HttpListener to listen for incoming requests on http://localhost:8080/. The server will continuously wait for requests using the GetContext method. When a request is received, we construct a response and send it back to the client.

Note that in a real web server, you would need to handle different types of requests and responses, and handle errors and exceptions. However, this basic example should give you an idea of how to set up a simple web server in C#.

gistlibby LogSnag