1

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

readByteCount = 487 (12 characters short)

What am I missing here? The body is multipart form data if that makes any difference.

Chris Kooken
  • 32,730
  • 15
  • 85
  • 123

2 Answers2

1
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 ;))

Community
  • 1
  • 1
Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
0

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?

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171