create a http server and read the request body as binary and return a binary response in csharp

Below is an example of creating an HTTP server in C# that reads the request body as binary and returns a binary response:

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

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();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            using (var ms = new MemoryStream())
            {
                request.InputStream.CopyTo(ms);
                byte[] requestBody = ms.ToArray();
                // Do something with the request body

                byte[] responseBody = Encoding.UTF8.GetBytes("Hello, World!");
                response.ContentType = "application/octet-stream";
                response.OutputStream.Write(responseBody, 0, responseBody.Length);
            }

            response.Close();
        }
    }
}
1032 chars
36 lines

In this example, we create an instance of HttpListener, add a prefix to listen for incoming requests, and start the server. We then enter an infinite loop to handle incoming requests.

For each request, we get the request and response objects from the HttpListenerContext. We create a MemoryStream and copy the input stream of the request into the memory stream as binary. We can then do something with the binary request data.

We create a binary response by encoding a string as UTF8 and writing it to the output stream of the response object. We also set the content type to application/octet-stream to indicate that the response is binary.

Finally, we close the output stream of the response object to indicate that we are done writing the response.

Note that this example does not handle errors or support multiple requests concurrently.

gistlibby LogSnag