日期:2014-05-16  浏览次数:20348 次

浅谈对node.js http.agent的理解

node.js之火已经燃起。本文简单介绍一下自己在学习node.js过程中遇到的问题。

node.js的http模块使用了一个agent代理。如果你的http启动了keep-alive那么这个代理相当于一个连接池。

这个代理维护了一定数量的socket链接,当然都是短链接。http发起请求所用的socket都是通过代理获取的。

这样就省去了每次发起http请求是创建套接字的时间提高了效率。

?

下面就说说这个agent中的主要属性:

对node v0.4的版本

agent.maxSockets? 默认值为5,指定代理能同时并发打开的套接字数量。

agent.sockets??? 当前正在被使用的套接字数组。使用数组的length属性可以查看值

agent.queue 待发送的套接字的个数。用length属性查看值,当并发发情的套接字超过

agent.maxSockets指定的值时就会把超过的部分放到quene中,呆有空闲链接的时候发送

node v0.6和v0.4在这个地方那个有了很大的区别,0.6不再提供http.getAgent方法,取而代之的是http.globalAgent

,这个方法获取的是一个全局的代理,对这个代理设置的允许并发打开的套接字数量agent.maxSockets对所有的ip+port有效。

0.6以后版本获取当前使用的套接字个数的方法:

agent.sockets['ip:port'].length

但是0.6版本的agent貌似不起作用,我查看tcp链接的时候每次访问都会重建链接,哪位大侠给说说是不是我用的不对啊。

1 楼 Mybeautiful 2012-03-09  
博主你好,
看到一段代码,
var httpAgent = require('http-agent'),
    util = require('util');

var agent = httpAgent.create('www.google.com', ['finance', 'news', 'images']);

agent.addListener('next', function (err, agent) {
  console.log('Body of the current page: ' + agent.body);
  console.log('Response we saw for this page: ' + util.inspect(agent.response));

  // Go to the next page in the sequence
  agent.next();
});

agent.addListener('stop', function (err, agent) {
  console.log('the agent has stopped');
});

agent.start();


可以遍历www.google.com的 finace,news,images,并打印出来,但是现在的问题是,如果 不是简单的打印,而是 分别从 finace,news,images,取点信息,然后一起返回到浏览器怎么做?