Nodejs学习记录:http模块

栏目: Node.js · 发布时间: 6年前

内容简介:http模块源码:我们不难发现,http 模块提供三个主要的函数: http.request, http.get, http.createServer。前两个函数主要是为了创建 http 客户端,向其它服务器发送请求,http.get 只是 http.request 的发送 get 请求的便捷方式;而 http.createServer 是为了创建 Node 服务,比如 Koa 服务框架就是基于 http.createServer 封装的。

概览

http模块源码: https://github.com/nodejs/nod...

function createServer(opts, requestListener) {
  return new Server(opts, requestListener);
}

function request(url, options, cb) {
  return new ClientRequest(url, options, cb);
}

function get(url, options, cb) {
  var req = request(url, options, cb);
  req.end();
  return req;
}

我们不难发现,http 模块提供三个主要的函数: http.request, http.get, http.createServer。前两个函数主要是为了创建 http 客户端,向其它服务器发送请求,http.get 只是 http.request 的发送 get 请求的便捷方式;而 http.createServer 是为了创建 Node 服务,比如 Koa 服务框架就是基于 http.createServer 封装的。

http.Agent

http.Agent 主要是为 http.request, http.get 提供代理服务的,用于管理 http 连接的创建,销毁及复用工作。http.request, http.get 默认使用 http.globalAgent 作为代理,每次请求都是“建立连接-数据传输-销毁连接”的过程,如果我们想让多个请求复用同一个 connection,则需要重新定义 agent 去覆盖默认的 http.globalAgent,下面我们看一下新建一个agent的需要哪些主要参数:

  • keepAlive:{Boolean} 是否开启 keepAlive,多个请求公用一个 socket connection,默认是 false。
  • maxSockets:{Number} 每台主机允许的socket的最大值,默认值为Infinity。
  • maxFreeSockets:{Number} 处于连接池空闲状态的最大连接数, 仅当开启 keepAlive 才有效。
let http = require('http');
const keepAliveAgent = new http.Agent({ 
    keepAlive: true,
    maxScokets: 1000,
    maxFreeSockets: 50 
})
http.get({
  hostname: 'localhost',
  port: 80,
  path: '/',
  agent: keepAliveAgent 
}, (res) => {
  // Do stuff with response
});

只有向相同的 host 和 port 发送请求才能公用同一个 keepAlive 的 socket 连接,如果开启 keepAlive ,同一时间内多个请求会被放在队列里等待;如果当前队列为空,该 socket 处于空闲状态,但是不会被销毁,等待下一次请求的到来。

使用 keepAlive 代理,有效的减少了建立/销毁连接的开销,开发者可以对连接池进行动态管理。

大体差不多就是这个意思,详细可以看 Node.js 官方文档

参考

https://nodejs.org/docs/lates...


以上所述就是小编给大家介绍的《Nodejs学习记录:http模块》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Programming in Java

Introduction to Programming in Java

Robert Sedgewick、Kevin Wayne / Addison-Wesley / 2007-7-27 / USD 89.00

By emphasizing the application of computer programming not only in success stories in the software industry but also in familiar scenarios in physical and biological science, engineering, and appli......一起来看看 《Introduction to Programming in Java》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具