开发手册 欢迎您!
软件开发者资料库

HTTP2 | Node.js

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。Node.js 的包管理器 npm,是全球最大的开源库生态系统。

Node.js v8.x 中文文档


目录

HTTP2#

Stability: 1 - Experimental

The http2 module provides an implementation of the HTTP/2 protocol. Itcan be accessed using:

const http2 = require('http2');

Core API#

The Core API provides a low-level interface designed specifically aroundsupport for HTTP/2 protocol features. It is specifically not designed forcompatibility with the existing HTTP/1 module API. However,the Compatibility API is.

The http2 Core API is much more symmetric between client and server than thehttp API. For instance, most events, like error and socketError, can beemitted either by client-side code or server-side code.

Server-side example#

The following illustrates a simple, plain-text HTTP/2 server using theCore API:

const http2 = require('http2');const fs = require('fs');const server = http2.createSecureServer({  key: fs.readFileSync('localhost-privkey.pem'),  cert: fs.readFileSync('localhost-cert.pem')});server.on('error', (err) => console.error(err));server.on('socketError', (err) => console.error(err));server.on('stream', (stream, headers) => {  // stream is a Duplex  stream.respond({    'content-type': 'text/html',    ':status': 200  });  stream.end('

Hello World

');});server.listen(8443);

To generate the certificate and key for this example, run:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \  -keyout localhost-privkey.pem -out localhost-cert.pem

Client-side example#

The following illustrates an HTTP/2 client:

const http2 = require('http2');const fs = require('fs');const client = http2.connect('https://localhost:8443', {  ca: fs.readFileSync('localhost-cert.pem')});client.on('socketError', (err) => console.error(err));client.on('error', (err) => console.error(err));const req = client.request({ ':path': '/' });req.on('response', (headers, flags) => {  for (const name in headers) {    console.log(`${name}: ${headers[name]}`);  }});req.setEncoding('utf8');let data = '';req.on('data', (chunk) => { data += chunk; });req.on('end', () => {  console.log(`\n${data}`);  client.destroy();});req.end();

Class: Http2Session#

  • Extends:

Instances of the http2.Http2Session class represent an active communicationssession between an HTTP/2 client and server. Instances of this class are notintended to be constructed directly by user code.

Each Http2Session instance will exhibit slightly different behaviorsdepending on whether it is operating as a server or a client. Thehttp2session.type property can be used to determine the mode in which anHttp2Session is operating. On the server side, user code should rarelyhave occasion to work with the Http2Session object directly, with mostactions typically taken through interactions with either the Http2Server orHttp2Stream objects.

Http2Session and Sockets#

Every Http2Session instance is associated with exactly one net.Socket ortls.TLSSocket when it is created. When either the Socket or theHttp2Session are destroyed, both will be destroyed.

Because the of the specific serialization and processing requirements imposedby the HTTP/2 protocol, it is not recommended for user code to read data fromor write data to a Socket instance bound to a Http2Session. Doing so canput the HTTP/2 session into an indeterminate state causing the session andthe socket to become unusable.

Once a Socket has been bound to an Http2Session, user code should relysolely on the API of the Http2Session.

Event: 'close'#

The 'close' event is emitted once the Http2Session has been terminated.

Event: 'connect'#

The 'connect' event is emitted once the Http2Session has been successfullyconnected to the remote peer and communication may begin.

Note: User code will typically not listen for this event directly.

Event: 'error'#

The 'error' event is emitted when an error occurs during the processing ofan Http2Session.

Event: 'frameError'#

The 'frameError' event is emitted when an error occurs while attempting tosend a frame on the session. If the frame that could not be sent is associatedwith a specific Http2Stream, an attempt to emit 'frameError' event on theHttp2Stream is made.

When invoked, the handler function will receive three arguments:

  • An integer identifying the frame type.
  • An integer identifying the error code.
  • An integer identifying the stream (or 0 if the frame is not associated witha stream).

If the 'frameError' event is associated with a stream, the stream will beclosed and destroyed immediately following the 'frameError' event. If theevent is not associated with a stream, the Http2Session will be shutdownimmediately following the 'frameError' event.

Event: 'goaway'#

The 'goaway' event is emitted when a GOAWAY frame is received. When invoked,the handler function will receive three arguments:

  • errorCode The HTTP/2 error code specified in the GOAWAY frame.
  • lastStreamID The ID of the last stream the remote peer successfullyprocessed (or 0 if no ID is specified).
  • opaqueData If additional opaque data was included in the GOAWAYframe, a Buffer instance will be passed containing that data.

Note: The Http2Session instance will be shutdown automatically when the'goaway' event is emitted.

Event: 'localSettings'#

The 'localSettings' event is emitted when an acknowledgement SETTINGS framehas been received. When invoked, the handler function will receive a copy ofthe local settings.

Note: When using http2session.settings() to submit new settings, themodified settings do not take effect until the 'localSettings' event isemitted.

session.settings({ enablePush: false });session.on('localSettings', (settings) => {  /** use the new settings **/});

Event: 'remoteSettings'#

The 'remoteSettings' event is emitted when a new SETTINGS frame is receivedfrom the connected peer. When invoked, the handler function will receive a copyof the remote settings.

session.on('remoteSettings', (settings) => {  /** use the new settings **/});

Event: 'stream'#

The 'stream' event is emitted when a new Http2Stream is created. Wheninvoked, the handler function will receive a reference to the Http2Streamobject, a Headers Object, and numeric flags associated with the creationof the stream.

const http2 = require('http2');const {  HTTP2_HEADER_METHOD,  HTTP2_HEADER_PATH,  HTTP2_HEADER_STATUS,  HTTP2_HEADER_CONTENT_TYPE} = http2.constants;session.on('stream', (stream, headers, flags) => {  const method = headers[HTTP2_HEADER_METHOD];  const path = headers[HTTP2_HEADER_PATH];  // ...  stream.respond({    [HTTP2_HEADER_STATUS]: 200,    [HTTP2_HEADER_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 thenet.Server or tls.Server instances returned by http2.createServer() andhttp2.createSecureServer(), respectively, as in the example below:

const http2 = require('http2');// Create a plain-text HTTP/2 serverconst server = http2.createServer();server.on('stream', (stream, headers) => {  stream.respond({    'content-type': 'text/html',    ':status': 200  });  stream.end('

Hello World

');});server.listen(80);

Event: 'socketError'#

The 'socketError' event is emitted when an 'error' is emitted on theSocket instance bound to the Http2Session. If this event is not handled,the 'error' event will be re-emitted on the Socket.

For ServerHttp2Session instances, a 'socketError' event listener is alwaysregistered that will, by default, forward the event on to the owningHttp2Server instance if no additional handlers are registered.

Event: 'timeout'#

After the http2session.setTimeout() method is used to set the timeout periodfor this Http2Session, the 'timeout' event is emitted if there is noactivity on the Http2Session after the configured number of milliseconds.

session.setTimeout(2000);session.on('timeout', () => { /** .. **/ });

http2session.destroy()#

  • Returns:

Immediately terminates the Http2Session and the associated net.Socket ortls.TLSSocket.

http2session.destroyed#

  • Value:

Will be true if this Http2Session instance has been destroyed and must nolonger be used, otherwise false.

http2session.localSettings#

A prototype-less object describing the current local settings of thisHttp2Session. The local settings are local to this Http2Session instance.

http2session.pendingSettingsAck#

  • Value:

Indicates whether or not the Http2Session is currently waiting for anacknowledgement for a sent SETTINGS frame. Will be true after calling thehttp2session.settings() method. Will be false once all sent SETTINGSframes have been acknowledged.

http2session.ping([payload, ]callback)#

  • payload | | Optional ping payload.
  • callback
  • Returns:

Sends a PING frame to the connected HTTP/2 peer. A callback function mustbe provided. The method will return true if the PING was sent, falseotherwise.

The maximum number of outstanding (unacknowledged) pings is determined by themaxOutstandingPings configuration option. The default maximum is 10.

If provided, the payload must be a Buffer, TypedArray, or DataViewcontaining 8 bytes of data that will be transmitted with the PING andreturned with the ping acknowledgement.

The callback will be invoked with three arguments: an error argument that willbe null if the PING was successfully acknowledged, a duration argumentthat reports the number of milliseconds elapsed since the ping was sent and theacknowledgement was received, and a Buffer containing the 8-byte PINGpayload.

session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {  if (!err) {    console.log(`Ping acknowledged in ${duration} milliseconds`);    console.log(`With payload '${payload.toString()}`);  }});

If the payload argument is not specified, the default payload will be the64-bit timestamp (little endian) marking the start of the PING duration.

http2session.remoteSettings#

A prototype-less object describing the current remote settings of thisHttp2Session. The remote settings are set by the connected HTTP/2 peer.

http2session.request(headers[, options])#