2015-02-24 83 views
2

我编写了一个c#程序,该程序成功地连接到带代理和不带代理的远程主机。我们在两个不同的网络中工作,即使用代理的家庭和办公室网络。这是代码片段。如何从System.Net.WebException中恢复:当连接发生变化时无法连接到远程服务器

while(true) { 
    Thread.sleep(5000); 
    using (var client = new WebClient()) { 
    client.Headers[HttpRequestHeader.Accept] = "application/json"; 
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    string result = client.UploadString(Event.GetInsertURL(), "POST", json); 
    if (result.Contains("SUCCESS")) { 
     // Console.WriteLine("SUCCESS"); 
    } 
    } 
} 

上述代码运行在一个循环中,以保持对同一api的请求。如果程序在这些网络中启动,它就在两个网络中工作。但是,如果我在家中启动程序并进入休眠状态,或者在计算机上休眠并在办公室重新启动计算机,则会发生以下异常。

System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.130.141:443 
    at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) 

原因是第一次进行的连接在随后的请求中被重用。当我得到这个异常时,有没有办法强制创建连接?

P.S:

Event.GetInsertURL的代码()

public static string GetInsertURL(){ 
return "https://my-app.appspot.com/_ah/api/"eventendpoint/v1/insertEvents"; 
} 
+0

为什么不为每个请求创建一个连接?或者你不能在外部循环中捕获异常,然后建立一个新的连接并使用它? – 2015-03-03 07:10:54

+0

不知道如何建立新的连接。即使我们正在创建一个新的Web客户端,它看起来就是重用了连接。 – Buddha 2015-03-03 10:23:19

+0

你确定连接有问题吗?我有一种感觉,问题来自'Event.GetInsertURL()'。难道不是你试图将url解析为不同的IP地址,每个IP地址都独占其网络? – samy 2015-03-03 10:23:43

回答

0

的代码已创建为new WebClient()每个连接一个新的客户端会话。

这可能是睡眠发生在一个会话过程中,然后触发故障。

一般而言,任何网络方法都可能在意外情况下发生。唯一真正的解决方案是将代码封装在try/catch块中,并在报告永久性故障之前在正确的条件下重试几次。

0

基于以上知识经验:
使用HttpWebRequest而不是webClient,它只是更强大。
我的例子太乱了,但这是基础:
var httpWebRequest =(HttpWebRequest)System.Net.WebRequest.Create(URI);

相关问题