C# TCPListener Get POST request data

Mihai Floares 1 Reputation point
2022-01-19T04:21:33.99+00:00

I have this simple TCPListener HTTP request:
TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 44394);
tcpListener.Start();

            while (true)
            {
                Console.WriteLine("Listening...");

                TcpClient client = tcpListener.AcceptTcpClient();
                using (NetworkStream stream = client.GetStream())
                {
                    byte[] requestBytes = new byte[100000];

                    int readBytes = stream.Read(requestBytes, 0, requestBytes.Length);

                    var requestResult = Encoding.UTF8.GetString(requestBytes, 0, readBytes);
                    Console.WriteLine("------------Begin of Request------------");
                    Console.WriteLine(requestResult);
                    Console.WriteLine("------------End of Request------------");
                    Console.Write("\n\n\n");
                    TextReader fileReader = new StreamReader(websitePath);
                    string html = fileReader.ReadToEnd();

                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write("HTTP/1.1 200 Success");
                    writer.Write(Environment.NewLine);
                    writer.Write($"Content-Type: text/html");
                    writer.Write(Environment.NewLine);
                    writer.Write("Content-Length: " + html.Length);
                    writer.Write(Environment.NewLine);
                    writer.Write(Environment.NewLine);
                    writer.Write(html);
                    writer.Flush();



                }

            }
        }

And this index.html:
<h1>Hello world</h1>
<form action="" method=POST>
<input id=data type=text>
<input id=submit type = submit>
</form>

How to get in the c# the content of the input with the id data as a POST request?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,563 questions
Windows 10 Network
Windows 10 Network
Windows 10: A Microsoft operating system that runs on personal computers and tablets.Network: A group of devices that communicate either wirelessly or via a physical connection.
1,999 questions
{count} votes

1 answer

Sort by: Most helpful
  1. jona varque 1 Reputation point
    2022-03-06T23:13:28.85+00:00

    @Viorel I am doing pretty much the same with TcpListener. I did write up a test using HttpListener but it has to be run in admin mode to work. Since I can not do that I have coded up a test with TcpListener. Unless you know how to get HttpListener to work without admin mode? So now, I have the same question. How to properly parse the request with the same functionality as HttpListener. You're right though.. it is easier with HttpListener!