2014-01-23 144 views
3

我實際上面臨的問題與我的JavaScript代碼與node.js執行 我需要發送一個循環中的http請求到遠程服務器(我設置www.google.ca在代碼中)。 這裏是我的代碼:Node.js在循環中發送http請求

var http = require('http'); 

var options = { 
    hostname: 'www.google.ca', 
    port: 80, 
    path: '/', 
    method: 'GET' 
}; 

function sendRequest(options){ 
    console.log('hello'); 
    var start = new Date(); 
    var req = http.request(options,function(res) { 
     console.log('Request took:', new Date() - start, 'ms'); 
    }); 
    req.on('error', function(e) { 
     console.log('problem with request: ' + e.message); 
    }); 
    req.end(); 
}; 

for(var i=0;i<10;i++){ 
    sendRequest(options); 
} 

我的問題是,無論多少次,我通過我的圈,我得到的只有5首他們的響應。對於其餘的請求,函數sendRequest()被調用,但我沒有得到任何響應,既沒有錯誤消息。然後程序終止。 但是,當我將localhost設置爲主機時,它工作正常。 任何人都可以解決這個問題嗎? 在此先感謝!

+0

的[node.js的http.get 5個請求到遠程站點之後掛機]可能重複(http://stackoverflow.com/questions/16965582/node-js- http-get-hangs-5-requests-to-remote-site) – loganfsmyth

+0

遠程服務器限制並行請求的數量。嘗試連續發送這些請求。 – umair

回答

3

可能是您的機器或遠程機器因您提出的10個同時請求而不知所措。嘗試一次發送一個,您必須等到第一個請求完成後再繼續。一個簡單的方法,這樣做是async.timesSeries

var http = require('http'); 
var async = require('async'); 

var options = { 
    hostname: 'www.google.ca', 
    port: 80, 
    path: '/', 
    method: 'GET' 
}; 

function sendRequestWrapper(n, done){ 
    console.log('Calling sendRequest', n); 
    sendRequest(options, function(err){ 
    done(err); 
    }); 
}; 

function sendRequest(options, callback){ 
    //console.log('hello'); 
    var start = new Date(); 
    var req = http.request(options,function(res) { 
    // I don't know if this callback is called for error responses 
    // I have only used the `request` library which slightly simplifies this 
    // Under some circumstances you can accidentally cause problems by calling 
    // your callback function more than once (e.g. both here and on('error') 

    console.log('Request took:', new Date() - start, 'ms'); 
    callback(null); 
    }); 
    req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
    callback(err); 
    }); 
    req.end(); 
}; 

async.timesSeries(10, sendRequestWrapper);