'stream' 事件


创建新的 Http2Stream 时会触发 'stream' 事件。

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

在服务器端,用户代码通常不会直接监听此事件,而是为分别由 http2.createServer()http2.createSecureServer() 返回的 net.Servertls.Server 实例触发的 'stream' 事件注册句柄,如下例所示:

const http2 = require('node:http2');

// 创建未加密的 HTTP/2 服务器
const server = http2.createServer();

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html; charset=utf-8',
    ':status': 200
  });
  stream.on('error', (error) => console.error(error));
  stream.end('<h1>Hello World</h1>');
});

server.listen(80);

即使 HTTP/2 流和网络套接字不是 1:1 对应,网络错误也会破坏每个单独的流,必须在流级别上处理,如上所示。

The 'stream' event is emitted when a new Http2Stream is created.

const http2 = require('node:http2');
session.on('stream', (stream, headers, flags) => {
  const method = headers[':method'];
  const path = headers[':path'];
  // ...
  stream.respond({
    ':status': 200,
    'content-type': 'text/plain; charset=utf-8'
  });
  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('node:http2');

// Create an unencrypted HTTP/2 server
const server = http2.createServer();

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html; charset=utf-8',
    ':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.