EADDRNOTAVAIL after many http.get requests to loca

2019-02-09 14:26发布

问题:

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

When broken:

  • I cannot do a http.request to localhost for (round about) 10 seconds (EADDRNOTAVAIL)

While these 10 seconds

  • 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)

After 10 seconds

  • I can do a http.request to localhost again (as if node.js has healed itself)

This is the code:

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!");
});

回答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
        },
...

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
        },
...

I have posted this issue also on GitHub.



回答2:

MacOS solution , or at least what worked for me

and sending the request to mac.local