EADDRNOTAVAIL经过多次对localhost的http.get请求

hei*_*nob 8 httprequest node.js

在我获得28233个请求后,对localhost(Apache)做了很多http.get请求EADDRNOTAVAIL.

坏了的时候:

  • 不能为localhost 一个http.request for(round)10秒(EADDRNOTAVAIL)

这10秒钟

  • 能做到 curl http://localhost (Apache没有错误,它仍然像魅力一样工作)
  • 可以做 一个http.get-request(从node.js)到www.google.com(该错误只影响对localhost的请求)

10秒后

  • 可以再次对localhost 执行 http.request(就好像node.js已经自愈了)

这是代码:

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!");
});
Run Code Online (Sandbox Code Playgroud)

hei*_*nob 11

我通过覆盖默认的全局代理找到了解决方案.一种可能性是设置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
        },
...
Run Code Online (Sandbox Code Playgroud)

通过此更正,上述示例有效.但我仍然有EADDRNOTAVAIL问题中我的生产代码,所以设置agentfalse终于做到了:

var http = require( "http");

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

我也在GitHub上发布了这个问题.