目标机器主动拒绝无法连接? [英] No connection could be made because the target machine actively refused it?

查看:42
本文介绍了目标机器主动拒绝无法连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我在对 WebService 执行 HttpWebRequest 时收到以下错误.我也在下面复制了我的代码.

<小时><前>System.Net.WebException: 无法连接到远程服务器 ---> System.Net.Sockets.SocketException: 由于目标机器主动拒绝,无法建立连接 127.0.0.1:80在 System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)在 System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)在 System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)--- 内部异常堆栈跟踪结束 ---在 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;如果 (url.IndexOf("asmx") > 0 && parStartIndex > 0){AppHelper.Logger.Append("#############" + sla.ServiceName);使用 (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream())){而(真){int index01 = parList.Length;int index02 = parList.IndexOf("=");如果 (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));如果(index01 == parList.Length)休息;reqWriter.Write("&");parList = parList.Substring(index01 + 1);}}}别的{request.ContentLength = 0;}response = (HttpWebResponse)request.GetResponse();

解决方案

如果这总是发生,它的字面意思是这台机器存在但它没有在指定端口上侦听的服务,或者防火墙阻止了你.

如果它偶尔发生——你使用了有时"这个词——并且重试成功,很可能是因为服务器有一个完整的积压".

当您在侦听套接字上等待 accept 时,您将处于积压状态.此积压是有限的且相当短 - 值 1、2 或 3 并不罕见 - 因此操作系统可能无法将您的请求排队以供接受"使用.

backlog 是 listen 函数的一个参数 - 所有语言和平台在这方面都有基本相同的 API,即使是 C# 一.如果您控制服务器,则此参数通常是可配置的,并且可能从某些设置文件或注册表中读取.调查如何配置您的服务器.

如果您编写了服务器,则在接受套接字时可能会进行繁重的处理,这可以更好地移动到单独的工作线程中,以便您的接受始终准备好接收连接.您可以探索多种架构选择,以减少客户端排队并按顺序处理它们.

无论是否可以增加服务器积压,您都需要在客户端代码中使用重试逻辑来应对此问题 - 作为即使有很长的积压,服务器当时也可能在该端口上接收到大量其他请求.

如果用于映射的端口耗尽,NAT 路由器极有可能会出现此错误.不过,我认为我们可以放弃这种可能性,因为它太远了,因为路由器在耗尽之前有 64K 同时连接到同一目标地址/端口.

Sometimes I get the following error while I was doing HttpWebRequest to a WebService. I copied my code below too.


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();

解决方案

If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.

If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.

When you are waiting to be accepted on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.

The backlog is a parameter on the listen function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.

If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.

Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.

There is a rare possibility where a NAT router would give this error should its ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.

这篇关于目标机器主动拒绝无法连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆