In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how nodejs implements http2 push information. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
In the http1.x era, servers could not push messages to clients, which became a standard in http2.
HTTP/2 is designed to address many of the shortcomings of HTTP/1.x. The failure of the server to push messages to the client is a flaw, which is explained by a case.
If a web page depends on a lot of resources, such as js, css, pictures, etc. After the browser obtains the HTML in HTTP/1.x, it starts to scan the entire web page quickly, and then downloads some key resources such as js and css. There is a bottleneck in this process, that is, if the browser wants to scan html, it must first load html, and only after loading html can it scan out the key resources. In the process of loading html, the loading of css and js can only be downloaded after html loading, which creates an idle moment. The request process of HTTP1.x is shown in the figure:
Looking at the picture, it is found that css and js must wait until the html is loaded before the browser can request css and js resources.
To improve latency, HTTP/2 introduces server push, which allows the server to push resources to the browser before the browser explicitly requests it. A server knows exactly what additional resources are needed for a page (of course, these require developer configuration), and when it responds to the browser's first request, it can start pushing these resources synchronously.
The HTTP2 request process is shown in the figure:
Comparing the two pictures, we find that under the http2 protocol, if the browser requests a web page, the server will return both css and js resources when returning html resources.
This is the push process of http2. How is it implemented here? It should be noted that in the previous article, we learned that http2 is full-duplex communication and transmits information based on stream. When a browser requests a web page, after the establishment of a tcp link channel, this channel is the implementation of full-duplex communication (full-duplex means that the channel can handle both the client's request and the server's response). When the server responds to html content Push both css and js to the client in the form of stream.
The specific implementation flow chart is as follows:
From the above, we learned that although the html information is returned to the client with css,js, it should be noted that although it is returned together, it uses a different stream. There is a special stream in the return html section, and there is also a corresponding stream in the return css and js. It can be understood that there is only one way from work to home, but you can take different buses.
From the figure above, we can see an interesting stipulation that the id of the stream that pushes the data is even, while the id of the stream that requests and responds to the request flow is odd. I guess this may be to facilitate the difference between push and non-push streams.
Then we use the http2 module of nodejs to implement the push function of http2. The code is as follows:
Const http2 = require ('http2'); const fs = require (' fs'); const PORT = 8443 server.key' / Certificate and Private key const key = fs.readFileSync ('. / server.key'); const cert= fs.readFileSync ('. / server.crt'); / / 1. Create server const server = http2.createSecureServer ({key, cert}, onRequest) / / 2. Start the server server.listen (PORT, (err) = > {if (err) {console.error (err) return} console.log (`Server listening on ${PORT} `)}) / / 3, set the request event function function onRequest (req) Res) {const reqPath = req.url = ='/'?'/ index.html': req.url / / print the id of the request stream and the id console.log of the response stream ("req.stream.id:", req.stream.id) Console.log ("res.stream.id:", res.stream.id); / / determine whether it is the home page if (reqPath ='/ index.html') {/ / push 1.js res.stream.pushStream ({': path':'/ 1.js'}, (err, pushStream, headers) = > {if (err) throw err; pushStream.respond ({': status': 200}) Console.log ("pushStream:", pushStream.id) pushStream.end ("console.log (1)");}); / / push 2.js res.stream.pushStream ({': path':'/ 2.js'}, (err, pushStream, headers) = > {if (err) throw err Console.log ("pushStream:", pushStream.id) pushStream.respond ({': status': 200}); pushStream.end ("console.log (2)");}); const fd = fs.openSync ('. / index.html', 'r'); const stat = fs.fstatSync (fd) Const headers = {'content-length': stat.size,' last-modified': stat.mtime.toUTCString (), 'content-type':' text/html'}; res.stream.respondWithFD (fd, headers);} else {res.end}}
Then let's take a look at the index.html code:
Documenthello world
Index.html code: very simple, a web page introduced 1.js and 2.js.
Server code: using http2 module to create a server is similar to https and http module, except that the browser must set a certificate when supporting http2, so we need to configure the certificate and secret key.
In the request event function, we determine whether the requested url is the home page. If it is the home page, we configure the push information through the res.stream.pushStream method. In essence, we configure a tream, this stream is an instance of the Http2Stream class, and res.stream.pushStream requires two parameters. The first parameter is an object. Configure the path of the stream in this object, and the client can use the stream through this path.
The second argument is a callback function, the first argument of the callback function is err, and the second argument is a stream, which is also an instance of the Http2Stream class.
How is this stream set up? We set it through two methods on the stream object, the respond method sets the header information of the stream, and the end method sets the body information of the stream, which corresponds to the header frame and the body frame in the flow.
After setting up the two streams that need to be pushed, let's set the response flow of the mainstream html. Here we use another method of the strem instance, respondWidthFD, to set the response flow. This method needs to set two parameters, the first of which is a file descriptor and the second of which is header information. The body information of the stream is stored in the file descriptor, and the response header information of the stream is stored in the header.
From the two sets of stream setting methods, we can see that the stream contains at least two parts of information, the header frame and the body frame.
In the code, we print the id value of the stream respectively. Let's run the code to take a look at the printed result. The result is shown in the figure:
We can see that as we said earlier, the id of the push stream is even, and the id of the non-push stream is odd.
Then we take a look at the screenshot of network in the browser:
We see that all resources respond to requests using the http2 protocol, while 1.js and 2.js are push while the server is responding to html, with only 1ms.
To sum up: this article mainly talks about the push principle of http2, and how to use nodejs's http2 module to build a http2 server to achieve push function.
A few points to note here are as follows:
1. Http2 push is based on streaming and full-duplex communication.
2. The id of push stream is even, while the id of non-push stream is odd.
3. The content pushed by the server is based on the needs of the client, and the front and rear engineers need to work together.
4. When pushing data, try to push key resources, such as css, js, key background images, etc., but try not to push non-critical resources.
5. There are two ways to configure stream instances in nodejs, respond and end or respondWidthFD. Either way, you need to set header information and body information.
Thank you for reading! This is the end of the article on "how nodejs implements http2 push information". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.