多次向本地主机发出http.get请求后,出现EADDRNOTAVAIL [英] EADDRNOTAVAIL after many http.get requests to localhost

查看:121
本文介绍了多次向本地主机发出http.get请求后,出现EADDRNOTAVAIL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在28233个请求之后对本地主机(Apache)执行许多http.get-requests时,我得到EADDRNOTAVAIL.

When doing many http.get-requests to localhost (Apache) after 28233 requests I get EADDRNOTAVAIL.

损坏时:

  • 不能做对本地主机的http.request持续了大约10秒钟(EADDRNOTAVAIL)
  • I cannot do a http.request to localhost for (round about) 10 seconds (EADDRNOTAVAIL)

这10秒钟

  • 可以做 curl http://localhost(Apache中没有错误,它仍然可以像魅力一样工作)
  • 可以(向node.js发送)到www.google.com的http.get-request(错误仅影响到本地主机的请求)
  • I can do curl http://localhost (there is no error in Apache, it is still working like charm)
  • I can do a http.get-request (from node.js) to www.google.com (the error only affects requests to localhost)

10秒后

  • 可以再次执行对本地主机的http.request(好像node.js自己已经治愈了)
  • I can do a http.request to localhost again (as if node.js has healed itself)

这是代码:

var http = require( "http");

function httpRequest( callback ) {
    var options = {
            host: 'localhost',
            port: 80,
            path: ''
        },
        data = "";

    http.get(options, function(resp){
        resp.on('data', function( chunk ){   
            data += chunk;
        }).on("end", function() {
            callback( null, data );
        });
    }).on("error", function(e){
            callback( e );
    });
}

function loop( i, callback ) {
    if( i < 100000 ) {
        httpRequest( function( err, data ) {
            if( err ) {
                console.log( "Error!", i, err );
                return;
            }
            if( i % 1000 === 0 ) {
                console.log( i );
            }
            loop( i+1, callback );
        });
    } else {
        callback();
    }
}

console.log( "GO!");
loop( 0, function() {
   console.log( "READY!");
});

推荐答案

我通过覆盖默认的全局代理找到了解决方案.一种可能性是设置maxSockets:1:

I have found the solution by overwriting the default global agent. One possibility is to set maxSockets:1:

var http = require( "http"),
    agent = new http.Agent( {maxSockets: 1} ); // <-- this is new

function httpRequest( callback ) {
    var options = {
            host: 'localhost',
            port: 80,
            path: '',
            agent: agent // <-- and this is new
        },
...

通过此更正,以上示例可以正常工作.但是我的生产代码中仍然出现了EADDRNOTAVAIL问题,所以agent设置为false终于做到了:

With this correction the example above works. But I still had the EADDRNOTAVAIL issue within my production code, so setting the agent to false did it finally:

var http = require( "http");

function httpRequest( callback ) {
    var options = {
            host: 'localhost',
            port: 80,
            path: '',
            agent: false // <-- here
        },
...

我也在 GitHub 上发布了此问题.

I have posted this issue also on GitHub.

这篇关于多次向本地主机发出http.get请求后,出现EADDRNOTAVAIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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