有时,当我对 WebService 执行 HttpWebRequest 时,会出现以下错误。我也复制了下面的代码。
<小时/>System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = v_Timeout * 1000;
if (url.IndexOf("asmx") > 0 && parStartIndex > 0)
{
AppHelper.Logger.Append("#############" + sla.ServiceName);
using (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream()))
{
while (true)
{
int index01 = parList.Length;
int index02 = parList.IndexOf("=");
if (parList.IndexOf("&") > 0)
index01 = parList.IndexOf("&");
string parName = parList.Substring(0, index02);
string parValue = parList.Substring(index02 + 1, index01 - index02 - 1);
reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));
if (index01 == parList.Length)
break;
reqWriter.Write("&");
parList = parList.Substring(index01 + 1);
}
}
}
else
{
request.ContentLength = 0;
}
response = (HttpWebResponse)request.GetResponse();
最佳答案
如果这种情况总是发生,则字面上意味着该计算机存在,但没有服务监听指定端口,或者有防火墙阻止您。
如果这种情况偶尔发生 - 您使用了“有时”一词 - 并且重试成功,则可能是因为服务器已满“积压”。
当您等待监听套接字接受
时,您将被置于积压状态。此积压是有限的且非常短 - 值 1、2 或 3 并不罕见 - 因此操作系统可能无法将您的请求排队以供“接受”使用。
积压是listen
函数上的一个参数 - 所有语言和平台在这方面都有基本相同的API,甚至是C# one 。如果您控制服务器,则此参数通常是可配置的,并且可能从某些设置文件或注册表中读取。研究如何配置您的服务器。
如果您编写了服务器,则可能会在套接字的接受中进行繁重的处理,并且可以更好地将其移至单独的工作线程,以便您的接受始终准备好接收连接。您可以探索多种架构选择,以减轻客户端排队和按顺序处理的情况。
无论您是否可以增加服务器积压,您都需要在客户端代码中使用重试逻辑来解决此问题 - 如即使积压很长,服务器当时也可能会在该端口上接收大量其他请求。
如果 NAT 路由器的映射端口耗尽,极有可能会出现此错误。我认为我们可以放弃这种可能性,因为可能性太大,因为路由器在耗尽之前有 64K 同时连接到同一目标地址/端口。
关于c# - 目标机主动拒绝导致无法连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415950/