3

I use HttpWebResponse.BeginGetResponse() method to make a request to my server. The request has AllowReadStreamBuffering set to false so that the data will not be buffered. In the "Request Complete" notification I do the following (no error handling code included):

HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(result);
BinaryReader streamReader = new BinaryReader(response.GetResponseStream());

try
{
    while ((readSize = streamReader.Read(buffer, 0, buffer.Length)) > 0)
    {
    ...
    }
}
catch (Exception)
{   // NEVER GET HERE!!
...
}

My problem is that I cannot detect connection errors during reading data from stream (during the while loop). The behavior is very strange: it finishes to read all data that the OS has in the cache and then returns 'readSize = 0' as in the case of "end of stream". I was expecting streamReader.Read() to throw an IOException exception but it does not! I tried to find a stream failed flag somewhere but it seems that there is none (Stream/BinaryReader/HttpWebResponse). Please help!

I tested this by using three scenarios and all had the same behavior:

  1. Using the phone-to-PC USB connection
    • Phone connected to Internet using the PC USB connection
    • After few streamReader.Read() successful calls I disable the PC network card
  2. Using WIFI connection
    • Phone connected to Internet using WIFI connection
    • After few streamReader.Read() successful calls I power off the WIFI router
  3. Using WIFI connection
    • Phone connected to Internet using WIFI connection
    • After few streamReader.Read() successful calls I remove WAN cable (so it has no Internet access).

Thank you! Mihai

Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
Mihai
  • 89
  • 6
  • At this moment it is 16K but this has no relevance. – Mihai Aug 04 '11 at 14:55
  • try making your own exception under the while loop, giving you more control of the situation...This may help you figure out what is going on more in depth. – Keeano Sep 22 '11 at 15:06
  • won't you expect an exception on the first two lines of your code instead of the Read() method. You already end the get request, so i don't necessarily expect an exception there. I would expect it to happen in the EndGetResponse() – invalidusername Sep 22 '11 at 22:07

1 Answers1

0

If you are not getting an exception then one option is to check the number of bytes read against response.ContentLength

calum
  • 1,580
  • 10
  • 11