处理网络断开连接 [英] Handling network disconnect
问题描述
我试图做长轮询与HttpWebRequest对象。
I am trying to do "long polling" with an HttpWebRequest object.
在我的C#应用程序,我想提出一个HTTP GET请求,使用HttpWebRequest的。再后来,我等与beginGetResponse响应()。我使用ThreadPool.RegisterWaitForSingleObject等待响应,或者超时(1分钟后)。
In my C# app, I am making an HTTP GET request, using HttpWebRequest. And then afterwards, I wait for the response with beginGetResponse(). I am using ThreadPool.RegisterWaitForSingleObject to wait for the response, or to timeout (after 1 minute).
我已经设置了目标Web服务器需要很长的时间来响应。所以,我有时间断开网络电缆。
I have set the target web server to take a long time to respond. So that, I have time to disconnect the network cable.
发送请求后,我拉网线。
After sending the request, I pull the network cable.
有没有办法得到一个例外,当这种情况发生?所以我不必等待超时?
Is there a way to get an exception when this happens? So I don't have to wait for the timeout?
而不是一个例外,1分钟超时到期后超时(从RegisterWaitForSingleObject)发生。
Instead of an exception, the timeout (from RegisterWaitForSingleObject) happens after the 1 minute timeout has expired.
有没有办法来确定网络连接去了?目前,这种情况是在Web服务器需要超过1分钟回应的情况下没有区别。
Is there a way to determine that the network connection went down? Currently, this situation is indistinguishable from the case where the web server takes more than 1 minute to respond.
推荐答案
我找到了解决办法
调用beginGetResponse之前,我可以呼吁HttpWebRequest的以下内容:
Before calling beginGetResponse, I can call the following on the HttpWebRequest:
req.ServicePoint.SetTcpKeepAlive( true, 10000, 1000)
我想这意味着,经过闲置10秒,客户端会发送一个TCP保持活动到服务器。这永葆如果网络连接断开,因为网线被拔掉将会失败。
I think this means that after 10 seconds of inactivity, the client will send a TCP "keep alive" over to the server. That keep alive will fail if the network connection is down because the network cable was pulled.
所以,当电缆被拉到,我一个永葆得到10秒内发送(最多),然后为BeginGetResponse回调发生。在回调,我得到和异常时,我打电话req.EndGetResponse()。
So, when the cable is pulled, I a keep alive gets sent within 10 seconds (at most), and then the callback for BeginGetResponse happens. In the callback, I get and exception when I call req.EndGetResponse().
我想这违背了长轮询的好处之一,虽然。由于我们仍然存在发送数据包。
I guess this defeats one of the benefits of long polling, though. Since we're still sending packets around.
这篇关于处理网络断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!