繁体   English   中英

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

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

在哪些情况下,您应该在节点中使用http模块而不是http2模块? 大多数人和图书馆似乎仍在使用http模块,尽管使用 HTTP/2 的连接速度更快并且大多数网站已经切换到它。 这是什么原因? 提前致谢。

HTTP/2 支持完整的请求和响应多路复用。 实际上,这意味着从您的浏览器到 web 服务器的连接可用于发送多个请求并接收多个响应。 这消除了为每个请求建立新连接所需的大量额外时间。

    /*
     * 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