private int blockingRead(NetworkStream stream, byte[] buffer, int index,
int count)
{
int bytesRead = 0;
while (!shouldStop && bytesRead < count) {
try {
int n = stream.Read(buffer, index + bytesRead, count - bytesRead);
if (n <= 0) {
// Failed to read.
return -1;
}
bytesRead += n;
} catch (IOException) {
// Read failed or timed out.
return -1;
} catch (ObjectDisposedException) {
// Socket closed.
return -1;
}
}
return bytesRead;
}