TransWikia.com

I'm just starting out with tasks. I need to know if there's a better way to do TAP for socket handling (serving a request)

Code Review Asked by honey the codewitch on December 6, 2021

I’ve got this quick and dirty little console app in C# to serve an HTTP/HTML page.

static void Main()
{
    // create a socket
    var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
    // bind to localhost:8080
    socket.Bind(new IPEndPoint(IPAddress.Loopback, 8080));
    socket.Listen(16); // listen
    // begin our accept task
    var t = socket.AcceptTaskAsync();
    // when we're done accepting process the request
    t.ContinueWith((task) =>
    {
        _ProcessRequest(socket, t);
    });
    // show a prompt and wait for a keypress to exit
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
            
}
static void _ProcessRequest(Socket socket,Task<Socket> t)
{
    Console.Write("Awaiting request...");

    t.ContinueWith((task1) =>
    {
        var s = t.Result;
        var rt = s.ReceiveHttpRequestAsync();
                
        rt.ContinueWith((task2) =>
        {
            Console.Write("Done: ");
            var req = rt.Result;
            Console.WriteLine(req.Method + " " + req.Url);

            // our html to send
            var html = "<html><head><title>Hello</title></head><body><h1>Hello World!</h1></body>";
            var headers = "HTTP/1.1 200 OKnDate: "
                + DateTime.Now.ToUniversalTime().ToString("r")
                + "nContent-Type: text/htmlnContent-Length: "
                + html.Length.ToString()
                + "nConnection: Closedn";
            s.SendAsync(headers + "n" + html, Encoding.UTF8)
                .ContinueWith((task3) =>
                {
                    s.DisconnectAsync(false);
                    t = socket.AcceptTaskAsync();
                    t.ContinueWith((task4) =>
                    {
                        _ProcessRequest(socket, t);
                    });
                }).Wait();
            s.Close();
        });
    });
}

I’m calling async TAP methods on a socket because I use an EAP->TAP adapter class that I built up from this code:
https://blogs.msdn.microsoft.com/pfxteam/2011/12/15/awaiting-socket-operations/
It appears to work, and it has little to do with my question, which has to do with handling incoming requests using TAP. I’ve also got HttpReceiveRequestAsync which I’ve used for a year and isn’t important here.

Basically what I’m trying to do is accept on a socket and then asynchronously serve the request, and then accept on a socket again to keep it going. The code works, but I don’t think it works right. For one thing, my _ProcessRequest() routine is getting called 3 times every time I refresh the browser (i’m using chrome) – i know chrome will sometimes initiate multiple requests but i think it will only do two. Edit: I figured out why this is, and it’s fine

Also this seems dodgy. I don’t know why but there’s code smell, and not just because I threw it together. I don’t trust it. Can anyone take a look and see if there isn’t a better way to do this? I’m pretty new at this.

Edit: I fixed it up and I trust it more now, but I just wanted to see if it could be improved, or if there is some better pattern for this. I don’t care about using async/await keywords unless it significantly eases things. Sometimes it does. Here I didn’t find much use.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP