简体   繁体   English

什么时候应该在 http2 上使用节点的 http?

[英]When should you use node's http over http2?

In which cases should you use the http module in node over the http2 module?在哪些情况下,您应该在节点中使用http模块而不是http2模块? The majority of people and libraries seem to still be using the http module, even though connections using HTTP/2 are faster and most websites have already switched to it.大多数人和图书馆似乎仍在使用http模块,尽管使用 HTTP/2 的连接速度更快并且大多数网站已经切换到它。 What's the reason for that?这是什么原因? Thanks in advance.提前致谢。

HTTP/2 enables full request and response multiplexing. HTTP/2 支持完整的请求和响应多路复用。 In practice, this means a connection made to a web server from your browser can be used to send multiple requests and receive multiple responses.实际上,这意味着从您的浏览器到 web 服务器的连接可用于发送多个请求并接收多个响应。 This gets rid of a lot of the additional time that it takes to establish a new connection for each request.这消除了为每个请求建立新连接所需的大量额外时间。

    /*
     * Example HTTP2 Server
     * Opening a full-duplex (stream) channel on port 6000
     *
     */
    
    // Dependencies
    var http2 = require('http2');
    
    // Init the server
    var server = http2.createServer();
    
    // On a stream, send back hello world html
    server.on('stream', function (stream, headers) {
      stream.respond({
        ':status': 200,
        'content-type': 'text/html',
      });
      stream.end('<html><body><p>Hello World</p></body></html>');
    });
    
    // Listen on 6000
    server.listen(6000);

/*
 * Example HTTP2 client
 * Connects to port 6000 and logs the response
 *
 */

// Dependencies
var http2 = require('http2');

// Create client
var client = http2.connect('http://localhost:6000');

// Create a request
var req = client.request({
  ':path': '/'
});

// When message is received, add the pieces of it together until you reach the end
var str = '';
req.on('data',function(chunk){
  str += chunk;
});

// When a message ends, log it out
req.on('end', function(){
  console.log(str);
});

// End the request
req.end();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM