阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      Node.js Http2Session stream 事件

      Node.js Http2Session stream 事件

      新增于: v8.4.0

      • streamA reference to the stream
      • headers < HTTP/2 Headers Object> An object describing the headers
      • flags < number> The associated numeric flags
      • rawHeaders < Array> An array containing the raw header names followed by their respective values.

      The ‘stream’ event is emitted when a new Http2Stream is created.

      const http2 = require('http2');
      session.on('stream', (stream, headers, flags) => {
        const method = headers[':method'];
        const path = headers[':path'];
        // ...
        stream.respond({
          ':status': 200,
          'content-type': 'text/plain'
        });
        stream.write('hello ');
        stream.end('world');
      });
      
      

      On the server side, user code will typically not listen for this event directly, and would instead register a handler for the ‘stream’ event emitted by the net.Server or tls.Server instances returned by http2.createServer() and http2.createSecureServer(), respectively, as in the example below:

      const http2 = require('http2');
      
      // Create an unencrypted HTTP/2 server
      const server = http2.createServer();
      
      server.on('stream', (stream, headers) => {
        stream.respond({
          'content-type': 'text/html',
          ':status': 200
        });
        stream.on('error', (error) => console.error(error));
        stream.end('<h1>Hello World</h1>');
      });
      
      server.listen(80);
      
      

      Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, a network error will destroy each individual stream and must be handled on the stream level, as shown above.


      更多内容请参考:Node.js HTTP2,或者通过 点击对应菜单 进行查看;


      目录
      本文目录
      目录