我实际上遇到了使用 node.js 执行的 javascript 代码的问题
我需要循环发送http请求到远程服务器(我在代码中设置了www.google.ca)。
这是我的代码:
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 设置为主机时,它工作正常。
有人能解决这个问题吗?
提前致谢 !
也许您的计算机或远程计算机因您同时发出的 10 个请求而不堪重负。尝试一次发送一个,您必须等到第一个请求完成才能继续。一种简单的方法是async.timesSeries https://github.com/caolan/async#timesseriesn-callback
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)