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

 hello簞調_290 发布于 2023-02-05 11:38

在我获得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!");
});

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

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

var http = require( "http");

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

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

1 个回答
  • 我通过覆盖默认的全局代理找到了解决方案.一种可能性是设置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问题中我的生产代码,所以设置agentfalse终于做到了:

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

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

    2023-02-05 11:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有