Node http createServer過程源碼解讀

node的入門就會寫這樣幾行簡單的代碼,而createServer的過程究竟發生什麼node

const http = require('http');
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(() => {
  console.log(`Server is running `);
});

問題1:request和response是什麼

首先在http.js代碼中socket

const Server = exports.Server = server.Server;

exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

createServer作的事情很簡單,只是new一個Server的實例,傳入回調函數,並返回server函數

const server = require('_http_server');能夠看到server來自_http_serverui

function Server(requestListener) {
  if (!(this instanceof Server)) return new Server(requestListener);
  net.Server.call(this, { allowHalfOpen: true });
  if (requestListener) {
    this.addListener('request', requestListener);
  }
  this.httpAllowHalfOpen = false;
  this.addListener('connection', connectionListener);
  this.timeout = 2 * 60 * 1000;
  this._pendingResponseData = 0;
}
util.inherits(Server, net.Server);

Server.prototype.setTimeout = function(msecs, callback) {
  this.timeout = msecs;
  if (callback)
    this.on('timeout', callback);
  return this;
};

exports.Server = Server;

Server繼承net.Server,且requestListener,做爲'request'事件的監聽器。this

在resOnFinish函數中,self.emit('request', req, res);觸發了request事件。prototype

  • res的來源
    var res = new ServerResponse(req);code

  • req的來源server

    • req來自parserOnIncoming的形參;
      parser.onIncoming = parserOnIncoming.bind(undefined, this, socket, state);而parser來自_http_common的parsers.alloc()。繼承

    • 在方法parserOnHeadersComplete中skipBody = parser.onIncoming(parser.incoming, shouldKeepAlive);傳入了request,
      parser.incoming = new IncomingMessage(parser.socket);說明傳入的request是IncomingMessage的實例事件

    • IncomingMessage = require('_http_incoming').IncomingMessage;
      _http_incoming中能夠看到util.inherits(IncomingMessage, Stream.Readable);因此IncomingMessage是繼承自Stream.Readable

問題2:何時執行回調函數

  • connectionListener中有parser.onIncoming = parserOnIncoming.bind(undefined, this, socket, state);

  • 在server的初始化時

    • this.on('request', requestListener);註冊request時加上執行回調操做

    • this.on('connection', connectionListener);註冊connection的Listener

  • parserOnIncoming方法中 server.emit('request', req, res);發出request;最後在parserOnHeadersComplete方法中調用onIncoming,也就是server裏的parserOnIncoming

  • 那麼何時會發出connection操做呢?

    • 在net.js中的onconnection方法中self.emit('connection', socket);

    • _listen2方法中this._handle.onconnection = onconnection;

    • 在listen裏調用listen2self._listen2(address, port, addressType, backlog, fd);

    • Server.prototype.listen = function() 中有對listen方法的調用,也就是說,當server調用listen,會出發connectionListener,進一步觸發parserOnIncoming,發出request和response,觸發requestListener也就是傳入的回調函數

相關文章
相關標籤/搜索