.NET socket webserver HTTP POST request body
I am doing an embedded project in C# and I have written a socket based web server. Everything works well, except I can't for the life of me get the request body. Content-Length says that there is 12 characters, but the socket.Recieve method only gets the headers.
while (true)
{
using (Socket clientSocket = listeningSocket.Accept())
{
IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
Debug.Print("Received request from " + clientIP.ToString());
var x = clientSocket.RemoteEndPoint;
int availableBytes = clientSocket.Available;
Debug.Print(DateTime.Now.ToString() + " " + availableBytes.ToString() + " request bytes available");
int bytesReceived = (availableBytes > maxRequestSize ? maxRequestSize : availableBytes);
if (bytesReceived > 0)
{
byte[] buffer = new byte[bytesReceived]; // Buffer probably should be larger than this.
int readByteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
using (Request r = new Request(clientSocket, Encoding.UTF8.GetChars(buffer)))
{
Debug.Print(DateTime.Now.ToString() + " " + r.URL);
if (requestReceived != null) requestReceived(r);
}
}
}
Thread.Sleep(10);
}
availableBytes
= 499
bytesReceived
= 499开发者_如何学JAVA
readByteCount
= 487 (12 characters short)
What am I missing here? The body is multipart form data if that makes any difference.
int bytesReceived = (availableBytes > maxRequestSize ? maxRequestSize : availableBytes);
If maxRequestSize
is 487, then you will get the results you describe.
Also remember Content-Length
is not bytes - it's octets: What's the "Content-Length" field in HTTP header? (OK I'm being pedantic - and octet is 8 bits ;))
I wonder how reliable that Available
property is. It looks like it's only useful for non-blocking sockets, and then only as a boolean flag saying that something is available.
Why not just read the stream in a loop parsing messages as you go?
精彩评论