c# - 如何从 System.Net.WebException : Unable to connect to the remote server when connection changes 中恢复

标签 c# webclient

我已经编写了一个 c# 程序,它可以成功连接到远程主机,无论是否使用代理。我们在两个不同的网络中工作,家庭和办公室网络,它们使用代理。这是代码片段。

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)

原因是第一次建立的连接在后续请求中被重用。当我收到此异常时,有什么办法可以强制创建连接吗?

附言:

Event.GetInsertURL()的代码

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

最佳答案

代码已经在 new WebClient() 中为每个连接创建了一个新的客户端 session 。

可能是sleep发生在其中一个session的过程中,然后触发了故障。

一般来说,任何网络方法都可能在意想不到的情况下抛出异常。唯一真正的解决方案是将代码包装在 try/catch block 中,并在报告永久性故障之前在正确的条件下重试几次。

关于c# - 如何从 System.Net.WebException : Unable to connect to the remote server when connection changes 中恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28688945/

相关文章:

c# - 使用 C# 重建更新的 VB6 COM 类替换

c# - Monogame/XNA 输入监听器或单击执行功能?

vb.net - 显示网站的特定部分

c# - 在 WebClient 异步下载文件时检测连接断开(在 C# 中)

c# - 奇怪的 WebClient 行为 : 1 computer hangs, 其他人不对同一个文件

c# - 尝试链接到 cshtml 页面上的 azure blob 文件

c# - 如果派生类没有覆盖方法,应该调用哪个版本?

c# - C#XmlSerializer会忽略xs:string以外的类型的xs:attribute

windows - Silverlight:编码 webClient 流

c# - 使用 C# API 从 Facebook 下载附件