连接丢失时 BinaryReader.Read 不会抛出 IOException
我使用 HttpWebResponse.BeginGetResponse() 方法向我的服务器发出请求。该请求已将AllowReadStreamBuffering 设置为false,以便数据不会被缓冲。在“请求完成”通知中,我执行以下操作(不包含错误处理代码):
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!!
...
}
我的问题是,在从流读取数据期间(在 while 循环期间),我无法检测到连接错误。这种行为非常奇怪:它完成读取操作系统在缓存中的所有数据,然后返回“readSize = 0”,就像“流结束”的情况一样。 我原以为streamReader.Read()会抛出IOException异常但它没有! 我试图在某处找到 stream failed 标志,但似乎没有(Stream/BinaryReader/HttpWebResponse)。请帮忙!
我使用三种场景进行了测试,所有场景都具有相同的行为:
- 使用手机到 PC 的 USB 连接
- 使用 PC USB 连接将手机连接到互联网
- 在成功调用几次streamReader.Read()后,我禁用了PC网卡
- 使用 WIFI 连接
- 手机使用 WIFI 连接到互联网
- 成功调用几次streamReader.Read()后,我关闭了WIFI路由器
- 使用 WIFI 连接
- 手机使用 WIFI 连接到互联网
- 在成功调用几次streamReader.Read()之后,我移除了WAN电缆(因此它无法访问互联网)。
谢谢你! 米哈伊
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:
- 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
- Using WIFI connection
- Phone connected to Internet using WIFI connection
- After few streamReader.Read() successful calls I power off the WIFI router
- 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您没有收到异常,那么一种选择是检查针对 response.ContentLength 读取的字节数
If you are not getting an exception then one option is to check the number of bytes read against response.ContentLength