The NetworkStream.DataAvailable
property is not a reliable way to detect the end of the response; if the response is split into multiple TCP packets and a packet has not yet been delivered at the moment you check DataAvailable
, then the property will return false, terminating your loop prematurely.
Apparently, your network connection is fast enough that Thread.Sleep(1)
provides sufficient time for each successive packet to arrive. On a slower connection, though, it might not be adequate.
For reliable communication, the client and the server need to agree on a way to signal the end of the response. For example:
- The server can send the length of the response as a prefix before the actual response. The client reads the length, and then it reads from the stream until it has received that number of bytes.
- The server can send a special terminator as a suffix after the actual response. The client reads from the stream until it encounters the terminator. (Obviously, the terminator cannot appear anywhere in the response itself.)
- The server can close the connection after it sends the entire response. The client reads from the stream until the connection is closed.