Node.js v23.8.0 文档


QUIC#

稳定性: 1.0 - 早期开发

¥Stability: 1.0 - Early development

源代码: lib/quic.js

'node:quic' 模块提供了 QUIC 协议的实现。要访问它,请使用 --experimental-quic 选项启动 Node.js 并:

¥The 'node:quic' module provides an implementation of the QUIC protocol. To access it, start Node.js with the --experimental-quic option and:

import quic from 'node:quic';const quic = require('node:quic');

该模块仅在 node: 方案下可用。

¥The module is only available under the node: scheme.

quic.connect(address[, options])#

启动新的客户端会话。

¥Initiate a new client-side session.

import { connect } from 'node:quic';
import { Buffer } from 'node:buffer';

const enc = new TextEncoder();
const alpn = 'foo';
const client = await connect('123.123.123.123:8888', { alpn });
await client.createUnidirectionalStream({
  body: enc.encode('hello world'),
}); 

默认情况下,每次调用 connect(...) 都会创建一个绑定到新的随机本地 IP 端口的新本地 QuicEndpoint 实例。要指定要使用的确切本地地址,或通过单个本地端口多路复用多个 QUIC 会话,请传递 endpoint 选项,并使用 QuicEndpointEndpointOptions 作为参数。

¥By default, every call to connect(...) will create a new local QuicEndpoint instance bound to a new random local IP port. To specify the exact local address to use, or to multiplex multiple QUIC sessions over a single local port, pass the endpoint option with either a QuicEndpoint or EndpointOptions as the argument.

import { QuicEndpoint, connect } from 'node:quic';

const endpoint = new QuicEndpoint({
  address: '127.0.0.1:1234',
});

const client = await connect('123.123.123.123:8888', { endpoint }); 

quic.listen(onsession,[options])#

  • onsession quic.OnSessionCallback

  • options quic.SessionOptions

  • 返回:<Promise> 对 quic.QuicEndpoint 的promise

    ¥Returns: <Promise> a promise for a quic.QuicEndpoint

配置端点以作为服务器进行监听。当远程对等方发起新会话时,将使用创建的会话调用给定的 onsession 回调。

¥Configures the endpoint to listen as a server. When a new session is initiated by a remote peer, the given onsession callback will be invoked with the created session.

import { listen } from 'node:quic';

const endpoint = await listen((session) => {
  // ... handle the session
});

// Closing the endpoint allows any sessions open when close is called
// to complete naturally while preventing new sessions from being
// initiated. Once all existing sessions have finished, the endpoint
// will be destroyed. The call returns a promise that is resolved once
// the endpoint is destroyed.
await endpoint.close(); 

默认情况下,每次调用 listen(...) 都会创建一个绑定到新的随机本地 IP 端口的新本地 QuicEndpoint 实例。要指定要使用的确切本地地址,或通过单个本地端口多路复用多个 QUIC 会话,请传递 endpoint 选项,并使用 QuicEndpointEndpointOptions 作为参数。

¥By default, every call to listen(...) will create a new local QuicEndpoint instance bound to a new random local IP port. To specify the exact local address to use, or to multiplex multiple QUIC sessions over a single local port, pass the endpoint option with either a QuicEndpoint or EndpointOptions as the argument.

最多,任何单个 QuicEndpoint 只能配置为作为服务器监听一次。

¥At most, any single QuicEndpoint can only be configured to listen as a server once.

类:QuicEndpoint#

¥Class: QuicEndpoint

QuicEndpoint 封装了 QUIC 的本地 UDP 端口绑定。它既可以用作客户端,也可以用作服务器。

¥A QuicEndpoint encapsulates the local UDP-port binding for QUIC. It can be used as both a client and a server.

new QuicEndpoint([options])#

  • options quic.EndpointOptions

endpoint.address#

端点绑定到的本地 UDP 套接字地址(如果有)。

¥The local UDP socket address to which the endpoint is bound, if any.

如果端点当前未绑定,则值将为 undefined。只读。

¥If the endpoint is not currently bound then the value will be undefined. Read only.

endpoint.busy#

endpoint.busy 设置为 true 时,端点将暂时拒绝创建新会话。读/写。

¥When endpoint.busy is set to true, the endpoint will temporarily reject new sessions from being created. Read/write.

// Mark the endpoint busy. New sessions will be prevented.
endpoint.busy = true;

// Mark the endpoint free. New session will be allowed.
endpoint.busy = false; 

当端点负载过重且需要在追赶时暂时拒绝新会话时,busy 属性很有用。

¥The busy property is useful when the endpoint is under heavy load and needs to temporarily reject new sessions while it catches up.

endpoint.close()#

正常关闭端点。当所有当前打开的会话关闭时,端点将关闭并销毁自身。一旦调用,新会话将被拒绝。

¥Gracefully close the endpoint. The endpoint will close and destroy itself when all currently open sessions close. Once called, new sessions will be rejected.

返回一个在端点被销毁时实现的promise。

¥Returns a promise that is fulfilled when the endpoint is destroyed.

endpoint.closed#

端点销毁后实现的promise。这将是 endpoint.close() 函数返回的相同promise。只读。

¥A promise that is fulfilled when the endpoint is destroyed. This will be the same promise that is returned by the endpoint.close() function. Read only.

endpoint.closing#

如果已调用 endpoint.close() 并且尚未完成关闭端点,则为 True。只读。

¥True if endpoint.close() has been called and closing the endpoint has not yet completed. Read only.

endpoint.destroy([error])#

通过强制立即关闭所有打开的会话来强制关闭端点。

¥Forcefully closes the endpoint by forcing all open sessions to be immediately closed.

endpoint.destroyed#

如果已调用 endpoint.destroy(),则为 True。只读。

¥True if endpoint.destroy() has been called. Read only.

endpoint.stats#

  • quic.QuicEndpoint.Stats

为活动会话收集的统计信息。只读。

¥The statistics collected for an active session. Read only.

endpoint[Symbol.asyncDispose]()#

调用 endpoint.close() 并返回在端点关闭时实现的promise。

¥Calls endpoint.close() and returns a promise that fulfills when the endpoint has closed.

类:QuicEndpoint.Stats#

¥Class: QuicEndpoint.Stats

端点收集的统计信息的视图。

¥A view of the collected statistics for an endpoint.

endpointStats.createdAt#

  • <bigint> 表示端点创建时刻的时间戳。只读。

    ¥<bigint> A timestamp indicating the moment the endpoint was created. Read only.

endpointStats.destroyedAt#

  • <bigint> 表示端点销毁时刻的时间戳。只读。

    ¥<bigint> A timestamp indicating the moment the endpoint was destroyed. Read only.

endpointStats.bytesReceived#

  • <bigint> 此端点接收的字节总数。只读。

    ¥<bigint> The total number of bytes received by this endpoint. Read only.

endpointStats.bytesSent#

  • <bigint> 此端点发送的字节总数。只读。

    ¥<bigint> The total number of bytes sent by this endpoint. Read only.

endpointStats.packetsReceived#

  • <bigint> 此端点成功接收的 QUIC 数据包总数。只读。

    ¥<bigint> The total number of QUIC packets successfully received by this endpoint. Read only.

endpointStats.packetsSent#

  • <bigint> 此端点成功发送的 QUIC 数据包总数。只读。

    ¥<bigint> The total number of QUIC packets successfully sent by this endpoint. Read only.

endpointStats.serverSessions#

  • <bigint> 此端点接收的对等发起会话总数。只读。

    ¥<bigint> The total number of peer-initiated sessions received by this endpoint. Read only.

endpointStats.clientSessions#

  • <bigint> 此端点发起的会话总数。只读。

    ¥<bigint> The total number of sessions initiated by this endpoint. Read only.

endpointStats.serverBusyCount#

  • <bigint> 由于端点被标记为繁忙而拒绝初始数据包的总次数。只读。

    ¥<bigint> The total number of times an initial packet was rejected due to the endpoint being marked busy. Read only.

endpointStats.retryCount#

  • <bigint> 此端点上 QUIC 重试的总次数。只读。

    ¥<bigint> The total number of QUIC retry attempts on this endpoint. Read only.

endpointStats.versionNegotiationCount#

  • <bigint> 由于 QUIC 版本不匹配而拒绝的会话总数。只读。

    ¥<bigint> The total number sessions rejected due to QUIC version mismatch. Read only.

endpointStats.statelessResetCount#

  • <bigint> 此端点处理的无状态重置总数。只读。

    ¥<bigint> The total number of stateless resets handled by this endpoint. Read only.

endpointStats.immediateCloseCount#

  • <bigint> 握手完成之前关闭的会话总数。只读。

    ¥<bigint> The total number of sessions that were closed before handshake completed. Read only.

类:QuicSession#

¥Class: QuicSession

QuicSession 表示 QUIC 连接的本地端。

¥A QuicSession represents the local side of a QUIC connection.

session.close()#

启动会话的正常关闭。允许现有流完成,但不会打开任何新流。一旦所有流都关闭,会话将被销毁。会话被销毁后,返回的promise将被实现。

¥Initiate a graceful close of the session. Existing streams will be allowed to complete but no new streams will be opened. Once all streams have closed, the session will be destroyed. The returned promise will be fulfilled once the session has been destroyed.

session.closed#

会话销毁后实现的promise。

¥A promise that is fulfilled once the session is destroyed.

session.destroy([error])#

立即销毁会话。所有流都将被销毁,会话将被关闭。

¥Immediately destroy the session. All streams will be destroys and the session will be closed.

session.destroyed#

如果已调用 session.destroy(),则为 True。只读。

¥True if session.destroy() has been called. Read only.

session.endpoint#

  • quic.QuicEndpoint

创建此会话的端点。只读。

¥The endpoint that created this session. Read only.

session.onstream#

  • quic.OnStreamCallback

当远程对等方启动新的流时调用的回调。读/写。

¥The callback to invoke when a new stream is initiated by a remote peer. Read/write.

session.ondatagram#

  • quic.OnDatagramCallback

当从远程对等方接收到新的数据报时调用的回调。读/写。

¥The callback to invoke when a new datagram is received from a remote peer. Read/write.

session.ondatagramstatus#

  • quic.OnDatagramStatusCallback

当数据报的状态更新时调用的回调。读/写。

¥The callback to invoke when the status of a datagram is updated. Read/write.

session.onpathvalidation#

  • quic.OnPathValidationCallback

当路径验证更新时调用的回调。读/写。

¥The callback to invoke when the path validation is updated. Read/write.

seesion.onsessionticket#

  • quic.OnSessionTicketCallback

当接收到新的会话票证时调用的回调。读/写。

¥The callback to invoke when a new session ticket is received. Read/write.

session.onversionnegotiation#

  • quic.OnVersionNegotiationCallback

当启动版本协商时调用的回调。读/写。

¥The callback to invoke when a version negotiation is initiated. Read/write.

session.onhandshake#

  • quic.OnHandshakeCallback

当 TLS 握手完成时调用的回调。读/写。

¥The callback to invoke when the TLS handshake is completed. Read/write.

session.createBidirectionalStream([options])#

打开一个新的双向流。如果未指定 body 选项,则传出流将半关闭。

¥Open a new bidirectional stream. If the body option is not specified, the outgoing stream will be half-closed.

session.createUnidirectionalStream([options])#

打开一个新的单向流。如果未指定 body 选项,则将关闭传出流。

¥Open a new unidirectional stream. If the body option is not specified, the outgoing stream will be closed.

session.path#

与会话关联的本地和远程套接字地址。只读。

¥The local and remote socket addresses associated with the session. Read only.

session.sendDatagram(datagram)#

向远程对等方发送不可靠的数据报,返回数据报 ID。如果数据报有效负载指定为 ArrayBufferView,则该视图的所有权将转移到底层流。

¥Sends an unreliable datagram to the remote peer, returning the datagram ID. If the datagram payload is specified as an ArrayBufferView, then ownership of that view will be transfered to the underlying stream.

session.stats#

  • quic.QuicSession.Stats

返回会话的当前统计信息。只读。

¥Return the current statistics for the session. Read only.

session.updateKey()#

启动会话的密钥更新。

¥Initiate a key update for the session.

session[Symbol.asyncDispose]()#

调用 session.close() 并返回会话关闭时实现的promise。

¥Calls session.close() and returns a promise that fulfills when the session has closed.

类:QuicSession.Stats#

¥Class: QuicSession.Stats

sessionStats.createdAt#

sessionStats.closingAt#

sessionStats.handshakeCompletedAt#

sessionStats.handshakeConfirmedAt#

sessionStats.bytesReceived#

sessionStats.bytesSent#

sessionStats.bidiInStreamCount#

sessionStats.bidiOutStreamCount#

sessionStats.uniInStreamCount#

sessionStats.uniOutStreamCount#

sessionStats.maxBytesInFlights#

sessionStats.bytesInFlight#

sessionStats.blockCount#

sessionStats.cwnd#

sessionStats.latestRtt#

sessionStats.minRtt#

sessionStats.rttVar#

sessionStats.smoothedRtt#

sessionStats.ssthresh#

sessionStats.datagramsReceived#

sessionStats.datagramsSent#

sessionStats.datagramsAcknowledged#

sessionStats.datagramsLost#

类:QuicStream#

¥Class: QuicStream

stream.closed#

流完全关闭后实现的promise。

¥A promise that is fulfilled when the stream is fully closed.

stream.destroy([error])#

立即突然销毁流。

¥Immediately and abruptly destroys the stream.

stream.destroyed#

如果已调用 stream.destroy(),则为 True。

¥True if stream.destroy() has been called.

stream.direction#

流的方向性。只读。

¥The directionality of the stream. Read only.

stream.id#

流 ID。只读。

¥The stream ID. Read only.

stream.onblocked#

  • quic.OnBlockedCallback

当流被阻止时调用的回调。读/写。

¥The callback to invoke when the stream is blocked. Read/write.

stream.onreset#

  • quic.OnStreamErrorCallback

当流重置时调用的回调。读/写。

¥The callback to invoke when the stream is reset. Read/write.

stream.readable#

stream.session#

  • quic.QuicSession

创建此流的会话。只读。

¥The session that created this stream. Read only.

stream.stats#

  • quic.QuicStream.Stats

流的当前统计信息。只读。

¥The current statistics for the stream. Read only.

类:QuicStream.Stats#

¥Class: QuicStream.Stats

streamStats.ackedAt#

streamStats.bytesReceived#

streamStats.bytesSent#

streamStats.createdAt#

streamStats.destroyedAt#

streamStats.finalSize#

streamStats.isConnected#

streamStats.maxOffset#

streamStats.maxOffsetAcknowledged#

streamStats.maxOffsetReceived#

streamStats.openedAt#

streamStats.receivedAt#

类型#

¥Types

类型:EndpointOptions#

¥Type: EndpointOptions

构造新的 QuicEndpoint 实例时传递的端点配置选项。

¥The endpoint configuration options passed when constructing a new QuicEndpoint instance.

endpointOptions.address#

如果未指定,端点将绑定到随机端口上的 IPv4 localhost

¥If not specified the endpoint will bind to IPv4 localhost on a random port.

endpointOptions.addressLRUSize#

作为性能优化,端点维护一个经过验证的套接字地址的内部缓存。此选项设置缓存的最大地址数。这是一个高级选项,用户通常不需要指定。

¥The endpoint maintains an internal cache of validated socket addresses as a performance optimization. This option sets the maximum number of addresses that are cache. This is an advanced option that users typically won't have need to specify.

endpointOptions.ipv6Only#

true 时,表示端点应仅绑定到 IPv6 地址。

¥When true, indicates that the endpoint should bind only to IPv6 addresses.

endpointOptions.maxConnectionsPerHost#

指定每个远程对等地址允许的最大并发会话数。

¥Specifies the maximum number of concurrent sessions allowed per remote peer address.

endpointOptions.maxConnectionsTotal#

指定最大并发会话总数。

¥Specifies the maximum total number of concurrent sessions.

endpointOptions.maxRetries#

指定每个远程对等地址允许的最大 QUIC 重试次数。

¥Specifies the maximum number of QUIC retry attempts allowed per remote peer address.

endpointOptions.maxStatelessResetsPerHost#

指定每个远程对等地址允许的最大无状态重置次数。

¥Specifies the maximum number of stateless resets that are allowed per remote peer address.

endpointOptions.retryTokenExpiration#

指定 QUIC 重试令牌被视为有效的时间长度。

¥Specifies the length of time a QUIC retry token is considered valid.

endpointOptions.resetTokenSecret#

指定用于生成 QUIC 重试令牌的 16 字节密钥。

¥Specifies the 16-byte secret used to generate QUIC retry tokens.

endpointOptions.tokenExpiration#

指定 QUIC 令牌被视为有效的时间长度。

¥Specifies the length of time a QUIC token is considered valid.

endpointOptions.tokenSecret#

指定用于生成 QUIC 令牌的 16 字节密钥。

¥Specifies the 16-byte secret used to generate QUIC tokens.

endpointOptions.udpReceiveBufferSize#

endpointOptions.udpSendBufferSize#

endpointOptions.udpTTL#

endpointOptions.validateAddress#

true 时,要求端点在建立新连接时使用重试数据包验证对等地址。

¥When true, requires that the endpoint validate peer addresses using retry packets while establishing a new connection.

类型:SessionOptions#

¥Type: SessionOptions

sessionOptions.alpn#

ALPN 协议标识符。

¥The ALPN protocol identifier.

sessionOptions.ca#

用于会话的 CA 证书。

¥The CA certificates to use for sessions.

sessionOptions.cc#

指定将使用的拥塞控制算法。必须设置为 'reno''cubic''bbr' 之一。

¥Specifies the congestion control algorithm that will be used . Must be set to one of either 'reno', 'cubic', or 'bbr'.

这是一个高级选项,用户通常不需要指定。

¥This is an advanced option that users typically won't have need to specify.

sessionOptions.certs#

用于会话的 TLS 证书。

¥The TLS certificates to use for sessions.

sessionOptions.ciphers#

支持的 TLS 1.3 密码算法列表。

¥The list of supported TLS 1.3 cipher algorithms.

sessionOptions.crl#

用于会话的 CRL。

¥The CRL to use for sessions.

sessionOptions.groups#

支持 TLS 1.3 密码组的列表。

¥The list of support TLS 1.3 cipher groups.

sessionOptions.keylog#

如果启用 TLS 键盘记录输出,则为 True。

¥True to enable TLS keylogging output.

sessionOptions.keys#

用于会话的 TLS 加密密钥。

¥The TLS crypto keys to use for sessions.

sessionOptions.maxPayloadSize#

指定最大 UDP 数据包有效负载大小。

¥Specifies the maximum UDP packet payload size.

sessionOptions.maxStreamWindow#

指定最大流流量控制窗口大小。

¥Specifies the maximum stream flow-control window size.

sessionOptions.maxWindow#

指定最大会话流量控制窗口大小。

¥Specifies the maxumum session flow-control window size.

sessionOptions.minVersion#

允许的最低 QUIC 版本号。这是一个高级选项,用户通常不需要指定。

¥The minimum QUIC version number to allow. This is an advanced option that users typically won't have need to specify.

sessionOptions.preferredAddressPolicy#
  • <string> 'use''ignore''default' 之一。

    ¥<string> One of 'use', 'ignore', or 'default'.

当远程对等方公布首选地址时,此选项指定是使用它还是忽略它。

¥When the remote peer advertises a preferred address, this option specifies whether to use it or ignore it.

sessionOptions.qlog#

如果应启用 qlog 输出,则为 True。

¥True if qlog output should be enabled.

sessionOptions.sessionTicket#

sessionOptions.handshakeTimeout#

指定在超时之前允许完成 TLS 握手的最大毫秒数。

¥Specifies the maximum number of milliseconds a TLS handshake is permitted to take to complete before timing out.

sessionOptions.sni#

目标对等服务器名称。

¥The peer server name to target.

sessionOptions.tlsTrace#

如果启用 TLS 跟踪输出,则为 True。

¥True to enable TLS tracing output.

sessionOptions.transportParams#
  • quic.TransportParams

用于会话的 QUIC 传输参数。

¥The QUIC transport parameters to use for the session.

sessionOptions.unacknowledgedPacketThreshold#

指定会话应允许的最大未确认数据包数。

¥Specifies the maximum number of unacknowledged packets a session should allow.

sessionOptions.verifyClient#

如果要求验证 TLS 客户端证书,则为 True。

¥True to require verification of TLS client certificate.

sessionOptions.verifyPrivateKey#

如果要求私钥验证,则为 True。

¥True to require private key verification.

sessionOptions.version#

要使用的 QUIC 版本号。这是一个高级选项,用户通常不需要指定。

¥The QUIC version number to use. This is an advanced option that users typically won't have need to specify.

类型:TransportParams#

¥Type: TransportParams

transportParams.preferredAddressIpv4#

transportParams.preferredAddressIpv6#

transportParams.initialMaxStreamDataBidiLocal#

transportParams.initialMaxStreamDataBidiRemote#

transportParams.initialMaxStreamDataUni#

transportParams.initialMaxData#

transportParams.initialMaxStreamsBidi#

transportParams.initialMaxStreamsUni#

transportParams.maxIdleTimeout#

transportParams.activeConnectionIDLimit#

transportParams.ackDelayExponent#

transportParams.maxAckDelay#

transportParams.maxDatagramFrameSize#

回调#

¥Callbacks

回调:OnSessionCallback#

¥Callback: OnSessionCallback

  • this quic.QuicEndpoint

  • session quic.QuicSession

当远程对等方发起新会话时调用的回调函数。

¥The callback function that is invoked when a new session is initiated by a remote peer.

回调:OnStreamCallback#

¥Callback: OnStreamCallback

  • this quic.QuicSession

  • stream quic.QuicStream

回调:OnDatagramCallback#

¥Callback: OnDatagramCallback

回调:OnDatagramStatusCallback#

¥Callback: OnDatagramStatusCallback

  • this quic.QuicSession

  • id <bigint>

  • status <string> 'lost''acknowledged' 之一。

    ¥status <string> One of either 'lost' or 'acknowledged'.

回调:OnPathValidationCallback#

¥Callback: OnPathValidationCallback

回调:OnSessionTicketCallback#

¥Callback: OnSessionTicketCallback

回调:OnVersionNegotiationCallback#

¥Callback: OnVersionNegotiationCallback

回调:OnHandshakeCallback#

¥Callback: OnHandshakeCallback

回调:OnBlockedCallback#

¥Callback: OnBlockedCallback

  • this quic.QuicStream

回调:OnStreamErrorCallback#

¥Callback: OnStreamErrorCallback

  • this quic.QuicStream

  • error <any>

诊断通道#

¥Diagnostic Channels

通道:quic.endpoint.created#

¥Channel: quic.endpoint.created

  • endpoint quic.QuicEndpoint

  • config quic.EndpointOptions

通道:quic.endpoint.listen#

¥Channel: quic.endpoint.listen

  • endpoint quic.QuicEndpoint

  • optoins quic.SessionOptions

通道:quic.endpoint.closing#

¥Channel: quic.endpoint.closing

  • endpoint quic.QuicEndpoint

  • hasPendingError <boolean>

通道:quic.endpoint.closed#

¥Channel: quic.endpoint.closed

  • endpoint quic.QuicEndpoint

通道:quic.endpoint.error#

¥Channel: quic.endpoint.error

  • endpoint quic.QuicEndpoint

  • error <any>

通道:quic.endpoint.busy.change#

¥Channel: quic.endpoint.busy.change

通道:quic.session.created.client#

¥Channel: quic.session.created.client

通道:quic.session.created.server#

¥Channel: quic.session.created.server

通道:quic.session.open.stream#

¥Channel: quic.session.open.stream

通道:quic.session.received.stream#

¥Channel: quic.session.received.stream

通道:quic.session.send.datagram#

¥Channel: quic.session.send.datagram

通道:quic.session.update.key#

¥Channel: quic.session.update.key

通道:quic.session.closing#

¥Channel: quic.session.closing

通道:quic.session.closed#

¥Channel: quic.session.closed

通道:quic.session.receive.datagram#

¥Channel: quic.session.receive.datagram

通道:quic.session.receive.datagram.status#

¥Channel: quic.session.receive.datagram.status

通道:quic.session.path.validation#

¥Channel: quic.session.path.validation

通道:quic.session.ticket#

¥Channel: quic.session.ticket

通道:quic.session.version.negotiation#

¥Channel: quic.session.version.negotiation

通道:quic.session.handshake#

¥Channel: quic.session.handshake

Node.js 中文网 - 粤ICP备13048890号