@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!
C# TCPListener Get POST request data

Mihai Floares
1
Reputation point
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?
{count} votes