首页 > 语言 > JavaScript > 正文

node.js的http.createServer过程深入解析

2024-05-06 15:38:21
字体:
来源:转载
供稿:网友

下面是nodejs创建一个服务器的代码。接下来我们一起分析这个过程。

var http = require('http');http.createServer(function (request, response) {  response.end('Hello World');}).listen(9297);

首先我们去到lib/http.js模块看一下这个函数的代码。

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

只是对_http_server.js做了些封装。我们继续往下看。

function Server(requestListener) { if (!(this instanceof Server)) return new Server(requestListener); net.Server.call(this, { allowHalfOpen: true }); // 收到http请求时执行的回调 if (requestListener) {  this.on('request', requestListener); } this.httpAllowHalfOpen = false; // 建立tcp连接的回调 this.on('connection', connectionListener); this.timeout = 2 * 60 * 1000; this.keepAliveTimeout = 5000; this._pendingResponseData = 0; this.maxHeadersCount = null;}util.inherits(Server, net.Server);

发现_http_server.js也没有太多逻辑,继续看lib/net.js下的代码。

function Server(options, connectionListener) { if (!(this instanceof Server))  return new Server(options, connectionListener); EventEmitter.call(this); // connectionListener在http.js处理过了 if (typeof options === 'function') {  connectionListener = options;  options = {};  this.on('connection', connectionListener); } else if (options == null || typeof options === 'object') {  options = options || {};  if (typeof connectionListener === 'function') {   this.on('connection', connectionListener);  } } else {  throw new errors.TypeError('ERR_INVALID_ARG_TYPE',                'options',                'Object',                options); } this._connections = 0; ...... this[async_id_symbol] = -1; this._handle = null; this._usingWorkers = false; this._workers = []; this._unref = false; this.allowHalfOpen = options.allowHalfOpen || false; this.pauseOnConnect = !!options.pauseOnConnect;}

至此http.createServer就执行结束了,我们发现这个过程还没有涉及到很多逻辑,并且还是停留到js层面。接下来我们继续分析listen函数的过程。该函数是net模块提供的。我们只看关键的代码。

Server.prototype.listen = function(...args) { // 处理入参,根据文档我们知道listen可以接收好几个参数,我们这里是只传了端口号9297 var normalized = normalizeArgs(args); // normalized = [{port: 9297}, null]; var options = normalized[0]; var cb = normalized[1]; // 第一次listen的时候会创建,如果非空说明已经listen过 if (this._handle) {  throw new errors.Error('ERR_SERVER_ALREADY_LISTEN'); } ...... listenInCluster(this, null, options.port | 0, 4,           backlog, undefined, options.exclusive);}function listenInCluster() {  ...  server._listen2(address, port, addressType, backlog, fd);}_listen2 = setupListenHandle = function() {  ......  this._handle = createServerHandle(...);  this._handle.listen(backlog || 511);}function createServerHandle() {  handle = new TCP(TCPConstants.SERVER);  handle.bind(address, port);}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选