I have an HTTP connection with the server side using System.IO.Stream.Read to read the HTTP request body message.
The problem is that once in a couple of minutes the server gets stuck on the Read statement and doesn’t continue until the socket timeout has been reached or the client has closed the connection.
int bytesRead = 0;
while (bytesRead < contentLength)
{
int got = stream.Stream.Read(buffer.Buffer, bytesRead, contentLength - bytesRead);
bytesRead += got;
}
-
It could happen if the stream did not have the amount of data specified by contentLength variable.
This is not the case because when following the tcp stream with WireShark I see that the whole message body (as specified by contentLength) has reached the server machine. -
It happens only in the first time that the while loop has been “used”, i.e. only in the first time that the stream didn’t have “contentLength” number of bytes to read in one try and the while loop had to be re-entered.
Why does it get stuck and does not continue reading data?
It seems like it had something to do with the fact that I was using the Read method of both the NetworkStream (that’s the call seen in the code above) and the StreamReader that was created by passing the NetworkStream object to it’s constructor.
The NetworkStream.Read was used to read the http request message body while the StreamReader.Read was used to read the rest of the request (startline, headers…).
Although the calls happened synchroniously by the same thread, it may have been the cause to the behavior I experienced.
When changing the code to work only with a Socket and perform the reading directly from the socket, it has fixed the problem.