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

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

问题描述

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

<小时><上一页>System.Net.WebException:无法连接到远程服务器---> System.Net.Sockets.SocketException:无法建立连接,因为目标机器主动拒绝它 127.0.0.1:80在 System.Net.Sockets.Socket.DoConnect(端点 endPointSnapshot,SocketAddress 套接字地址)在 System.Net.Sockets.Socket.InternalConnect(端点 remoteEP)在 System.Net.ServicePoint.ConnectSocketInternal(布尔连接失败,套接字 s4,套接字 s6,套接字和套接字,IPAddress 和地址,ConnectSocketState 状态,IAsyncResult asyncResult,Int32 超时,异常和异常)--- 内部异常堆栈跟踪结束 ---在 System.Net.HttpWebRequest.GetRequestStream()

<小时>

ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();HttpWebRequest 请求 = (HttpWebRequest)WebRequest.Create(url);request.PreAuthenticate = true;request.Credentials = networkCredential(sla);request.Method = WebRequestMethods.Http.Post;request.ContentType = "应用程序/x-www-form-urlencoded";request.Timeout = v_Timeout * 1000;if (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("=");if (parList.IndexOf("&") > 0)index01 = parList.IndexOf("&");字符串 parName = parList.Substring(0, index02);字符串 parValue = parList.Substring(index02 + 1, index01 - index02 - 1);reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));if (index01 == parList.Length)休息;reqWriter.Write("&");parList = parList.Substring(index01 + 1);}}}别的{request.ContentLength = 0;}响应 = (HttpWebResponse)request.GetResponse();

解决方案

如果总是出现这种情况,则字面意思是机器存在但没有服务在指定端口上侦听,或者有防火墙阻止你.

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

当您在侦听套接字上等待接受时,您将被置于积压中.这个积压是有限的并且很短 - 1、2 或 3 的值并不少见 - 因此操作系统可能无法将您的请求排队等待接受"消费.

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

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

无论是否可以增加服务器积压,您确实需要在客户端代码中使用 重试 逻辑来处理此问题 - 如即使有很长的积压,当时服务器也可能在该端口上接收到许多其他请求.

如果 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天全站免登陆