I have a function to request an update from the server. I provide the query and also indicate the expected length of the response.
public Byte[] GetUpdate(Byte[] query, int expLength)
{
var response = new Byte[expLength];
lock(Client)
{
Stream s = Client.GetStream();
s.Write(query, 0, query.Length);
var totalBytesRead = 0;
var numAttempts = 0;
while(totalBytesRead < expLength && numAttempts < MAX_RETRIES)
{
numAttempts++;
int bytes;
try
{
bytes = s.Read(response, totalBytesRead, expLength);
}
catch (Exception ex)
{
throw new IOException();
}
totalBytesRead += bytes;
}
if(totalBytesRead < expLength)
{
// should probably throw something here
throw new IOException();
}
}
return response;
}
I don't like the way I have written this code esp with two exception throwing. Is there a more elegant way to write the code?
bytes == 0). AbusingMAX_RETRIESfor that is ugly. \$\endgroup\$bytescan be0without reaching the end of the stream;MAX_RETRIESis liable to cause a failure with any significant latency. If you have a network stream, thenDataAvailableis your friend. Sad as it is,Asyncreads are the only sensible way I've found for network code if you want to support multiple clients (having written code just like this many times in the past). \$\endgroup\$