search
HomeWeb Front-endJS TutorialDetailed introduction to http implementation in NODEJS

This article mainly introduces the technical process and detailed analysis of the http implementation of NODEJS. Friends who need it can refer to it.

1. Foreword

At present, HTTP protocol is the most widely used network protocol on the Internet, and it is also the one that front-end ER has the most contact with. kind of agreement. By reading the implementation of the http module in nodejs, you can have a deeper understanding of the HTTP protocol. The HTTP protocol is an application layer protocol based on the TCP protocol, and its implementation is inseparable from the TCP/IP protocol family. As for code implementation, the http module depends on the net module.

As shown in the figure below: In nodejs, http transmits data through the net module, and after obtaining the data, it relies on HTTP_PARSER to parse the data.

2. Source code

Start an HTTP service

Starting an HTTP service in nodejs is very simple, just instantiate one Server object, and listens to a certain port:

const Server = require('./libs/http').Server
const server = new Server( function(req, res) { 
 res.writeHead(200)
 res.end('hello world')
})
server.listen(9999)

SERVER class

The Server class inherits from net.Server and listens to the 'connection' event.

In the Server class, two main things are done: 1. Initialize the NET module and establish TCP network monitoring 2. Monitor its own request event

When the client request comes, Server The instance will first listen to the 'connection' event, establish a TCP connection and expose the socket object in the connectionListener. Next, the HTTP module interacts with the client through the socket object.

When a request arrives, the Server will trigger its own request event and call the requestListener method, which is the callback function passed in when creating the Server instance.

new Server( function(req, res) { 
 res.writeHead(200)
 res.end('hello world')
})

Note: The socket object is similar to an implementation of the TCP protocol, through which data can be exchanged with the client. Note: In the connectionListener function, the parser instance is also initialized and an onIncoming function is bound to it. HTTP Parser
The entire parsing process is carried out in connectionListener. The socket obtains the data pushed by TCP through the 'data' event.

When the socket obtains the data, it will first parse the data, that is: parser.excute (), the parsing tool is parser. It is worth mentioning that in order to reuse parser, the author obtained it from a 'FreeList pool'.

...
const parser = parsers.alloc() 
...
connectionListener(socket) { 
  socket.on('data', socketOnData)

  // TCP推入数据,parser进行解析
  function socketOnData(d) {
    ...
    const ret = parser.execute(d)
    ...
  }
}

1. When TCP data arrives, execute() first

2. Following the clues, we find that parser.excute is Excute (node_http_parser.cc). Excute is just an outsourcing, and the specific work is done by http_parser_excute (http_parser.c).

node_http_parser.cc is just a layer of packaging for http_parser.c. http_parser.c relies on the 7 externally exposed callback periodic functions to interact with node_http_parser.cc for data.

3. http_parser.c has only two types of callbacks: HTTP_CB and HTTP_DATA_CB. Through overloading, 8 periodic functions are registered in these two types of functions, as shown below:

4. Although http_parser registers 8 callback functions, node_http_parser.cc only exposes four periods to the outside world. Function:

parserOnHeaders

parserOnHeadersComplete

parserOnBody

parserOnMessageComplete

5. When http_parser.c parses to on_headers_complete, execute HTTP_CB( on_headers_complete) callback function, as shown in the figure:

The kOnHeadersComplete callback function will be executed within the function, that is: parserOnHeadersComplete function (common.js)

6. At this time, the request header parsing is basically completed, and then create An instance of IncomingMessage, and then wrap the request header data into the instance.
Execute the onIncoming callback function and pass the obtained IncomingMessage instance as a parameter.

function parserOnHeadersComplete (versionMajor, versionMinor, headers, method, url, statusCode, statusMessage, upgrade, shouldKeepAlive) { 
  ...
  parser.incoming = new IncomingMessage(parser.socket)
  parser.incoming.httpVersionMajor = versionMajor
  parser.incoming.httpVersionMinor = versionMinor
  parser.incoming.httpVersion = versionMajor + '.' + versionMinor
  parser.incoming.url = url
  ...
  skipBody = parser.onIncoming(parser.incoming, shouldKeepAlive)

}

7. In parserOnIncoming, create a ServerResponse instance.

With two instances of req and res, the request event monitored by the server is triggered.

When Server is instantiated, requestListener is used as a function parameter to monitor the request event.

8. Back to when the Server was created:

const server = new Server( function(req, res) { 
  var data = ''
  req.on('data', function(chunk){
    console.log('chunk: ' + chunk)
    data += chunk;
  })
  res.writeHead(200)
  res.end('hello world')
})

To sum up, after http_parser parses the header, the request event will be triggered.

Where should the body data be placed? In fact, the body data will be placed in the stream until the user uses the data event to receive the data. In other words, when the request is triggered, the body will not be parsed.

3. Process sorting

The complete http request is as follows: - The client initiates an HTTP request and first triggers the connection event on the server side. Establish a TCP link.

After receiving the connection event, the Server establishes a TCP connection, exposes the socket, and listens to the 'data' event through the socket; it initializes http-parser to prepare for subsequent parsing of data.

The HTTP request data reaches the server, and the parser executes the execute method to parse. After the request header is successfully parsed, the request event is triggered through a callback.

At this point, we have received the request for this http request in the Server callback function

4. Conclusion

Since many of the underlying libraries of nodejs are written in C/C, it is very inconvenient during the reading and debugging process. When I read the source code myself, I only focused on the JS part of the source code. For example, TCP's three-way handshake and four-way wave are not delved into its implementation details. The above analysis does not involve the analysis of http-body. For network requests with body, the actual situation is more complicated, and some details are not fully understood. When I summarize and share next time, I will try my best to fill in all the missing details.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to obtain node elements using JS

How to implement WebSocket function using NodeJS

About the actual usage of log4js in Express

The above is the detailed content of Detailed introduction to http implementation in NODEJS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor