多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
## http ### server: http.createServer是为了创建 Node 服务,比如 Koa 服务框架就是基于 http.createServer 封装的。 [https://juejin.im/post/5a31d2276fb9a0452207839c](https://juejin.im/post/5a31d2276fb9a0452207839c) http.IncomingMessage是HTTP请求的信息,是后端开发者最关注的内容,一般由http.Server的request事件发送,并作为第一个参数传递,包含三个事件 * data:当请求体数据到来时,该事件被触发,该事件提供一个参数chunk,表示接受的数据,如果该事件没有被监听,则请求体会被抛弃,该事件可能会被调用多次(这与nodejs是异步的有关系) * end:当请求体数据传输完毕时,该事件会被触发,此后不会再有数据 * close:用户当前请求结束时,该事件被触发,不同于end,如果用户强制终止了传输,也是用close http.ServerResponse是返回给客户端的信息,决定了用户最终看到的内容,一般也由http.Server的request事件发送,并作为第二个参数传递,它有三个重要的成员函数,用于返回响应头、响应内容以及结束请求 * res.writeHead(statusCode,\[heasers\]):向请求的客户端发送响应头,该函数在一个请求中最多调用一次,如果不调用,则会自动生成一个响应头 * res.write(data,\[encoding\]):想请求的客户端发送相应内容,data是一个buffer或者字符串,如果data是字符串,则需要制定编码方式,默认为utf-8,在res.end调用之前可以多次调用 * res.end(\[data\],\[encoding\]):结束响应,告知客户端所有发送已经结束,当所有要返回的内容发送完毕时,该函数必需被调用一次,两个可选参数与res.write()相同。如果不调用这个函数,客户端将用于处于等待状态。 ### client http模块提供了两个函数 `http.request`和 `http.get`,功能是作为客户端向http服务器发起请求。 * http.request(options,callback) options是一个类似关联数组的对象,表示请求的参数,callback作为回调函数,http.request返回一个http.ClientRequest的实例。 options常用的参数有host、port(默认为80)、method(默认为GET)、path(请求的相对于根的路径,默认是“/”,其中querystring应该包含在其中,例如/search?query=byvoid)、headers(请求头内容) var http=require("http"); http.get(options,callback) 这个方法是http.request方法的简化版,唯一的区别是http.get自动将请求方法设为了GET请求,同时不需要手动调用req.end(),但是需要记住的是,如果我们使用http.request方法时没有调用end方法,服务器将不会收到信息。 ### 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 才有效。 ~~~text 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://link.zhihu.com/?target=https%3A//nodejs.org/docs/latest-v8.x/api/http.html%23http_new_agent_options) ## net net模块是同样是nodejs的核心模块。在http模块概览里提到,http.Server继承了net.Server,此外,http客户端与http服务端的通信均依赖于socket(net.Socket)。也就是说,做node服务端编程,net基本是绕不开的一个模块。 从组成来看,net模块主要包含两部分,了解socket编程的同学应该比较熟悉了: * net.Server:TCP server,内部通过socket来实现与客户端的通信。 * net.Socket:tcp/本地 socket的node版实现,它实现了全双工的stream接口。 http是单工的。 ```js /* In the node.js intro tutorial (http://nodejs.org/), they show a basic tcp server, but for some reason omit a client connecting to it. I added an example at the bottom. Save the following server in example.js: */ var net = require('net'); var server = net.createServer(function(socket) { socket.write('Echo server\r\n'); socket.pipe(socket); }); server.listen(1337, '127.0.0.1'); /* And connect with a tcp client from the command line using netcat, the *nix utility for reading and writing across tcp/udp network connections. I've only used it for debugging myself. $ netcat 127.0.0.1 1337 You should see: > Echo server */ /* Or use this example tcp client written in node.js. (Originated with example code from http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html.) */ var net = require('net'); var client = new net.Socket(); client.connect(1337, '127.0.0.1', function() { console.log('Connected'); client.write('Hello, server! Love, Client.'); }); client.on('data', function(data) { console.log('Received: ' + data); client.destroy(); // kill client after server's response }); client.on('close', function() { console.log('Connection closed'); }); ``` ## events ->EventEmitter ## fs