tls.createServer([options][, secureConnectionListener])


  • options <Object>

    • ALPNProtocols<string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 包含支持的 ALPN 协议的字符串数组 BufferTypedArrayDataView,或单个 BufferTypedArrayDataViewBuffer 应采用 [len][name][len][name]... 格式,例如 0x05hello0x05world,其中第一个字节是下一个协议名称的长度。传入数组通常要简单得多,例如 ['hello', 'world']。(协议应按优先级排序。)

      ¥ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> An array of strings, Buffers, TypedArrays, or DataViews, or a single Buffer, TypedArray, or DataView containing the supported ALPN protocols. Buffers should have the format [len][name][len][name]... e.g. 0x05hello0x05world, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. ['hello', 'world']. (Protocols should be ordered by their priority.)

    • ALPNCallback<Function> 如果设置,当客户端使用 ALPN 扩展打开连接时将调用此函数。一个参数将被传递给回调:包含 servernameprotocols 字段的对象,分别包含 SNI 扩展中的服务器名称(如果有)和 ALPN 协议名称字符串数组。回调必须返回 protocols 中列出的字符串之一(该字符串将作为选定的 ALPN 协议返回给客户端)或 undefined(以致命警报拒绝连接)。如果返回的字符串与客户端的 ALPN 协议之一不匹配,则会抛出错误。该选项不能与 ALPNProtocols 选项一起使用,设置这两个选项将引发错误。

      ¥ALPNCallback: <Function> If set, this will be called when a client opens a connection using the ALPN extension. One argument will be passed to the callback: an object containing servername and protocols fields, respectively containing the server name from the SNI extension (if any) and an array of ALPN protocol name strings. The callback must return either one of the strings listed in protocols, which will be returned to the client as the selected ALPN protocol, or undefined, to reject the connection with a fatal alert. If a string is returned that does not match one of the client's ALPN protocols, an error will be thrown. This option cannot be used with the ALPNProtocols option, and setting both options will throw an error.

    • clientCertEngine <string> 可以提供客户端证书的 OpenSSL 引擎的名称。已弃用。

      ¥clientCertEngine <string> Name of an OpenSSL engine which can provide the client certificate. Deprecated.

    • enableTrace <boolean> 如果为 true, 则 tls.TLSSocket.enableTrace() 将在新连接上调用。建立安全连接后可以启用跟踪,但必须使用此选项来跟踪安全连接设置。默认值:false

      ¥enableTrace <boolean> If true, tls.TLSSocket.enableTrace() will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. Default: false.

    • handshakeTimeout <number> 如果 SSL/TLS 握手未在指定的毫秒数内完成,则中止连接。每当握手超时时,tls.Server 对象上就会触发 'tlsClientError'。默认值:120000(120 秒)。

      ¥handshakeTimeout <number> Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A 'tlsClientError' is emitted on the tls.Server object whenever a handshake times out. Default: 120000 (120 seconds).

    • rejectUnauthorized <boolean> 如果不是 false,则服务器将拒绝任何未经提供的 CA 列表授权的连接。此选项仅在 requestCerttrue 时有效。默认值:true

      ¥rejectUnauthorized <boolean> If not false the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true. Default: true.

    • requestCert <boolean> 如果为 true,则服务器将从连接的客户端请求证书并尝试验证该证书。默认值:false

      ¥requestCert <boolean> If true the server will request a certificate from clients that connect and attempt to verify that certificate. Default: false.

    • sessionTimeout <number> 服务器创建的 TLS 会话将无法恢复之前的秒数。有关详细信息,请参阅 会话恢复。默认值:300

      ¥sessionTimeout <number> The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default: 300.

    • SNICallback(servername, callback) <Function> 如果客户端支持 SNI TLS 扩展,将调用的函数。调用时将传递两个参数:servernamecallbackcallback 是一个错误优先回调,它有两个可选参数:errorctxctxSecureContext 实例(如果提供)。tls.createSecureContext() 可用于获得正确的 SecureContext。如果使用非真的 ctx 参数调用 callback,则将使用服务器的默认安全上下文。如果未提供 SNICallback,则将使用具有高级 API 的默认回调(见下文)。

      ¥SNICallback(servername, callback) <Function> A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: servername and callback. callback is an error-first callback that takes two optional arguments: error and ctx. ctx, if provided, is a SecureContext instance. tls.createSecureContext() can be used to get a proper SecureContext. If callback is called with a falsy ctx argument, the default secure context of the server will be used. If SNICallback wasn't provided the default callback with high-level API will be used (see below).

    • ticketKeys<Buffer> 48 字节的加密强伪随机数据。有关详细信息,请参阅 会话恢复

      ¥ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudorandom data. See Session Resumption for more information.

    • pskCallback <Function> 对于 TLS-PSK 协商,请参阅 预共享密钥

      ¥pskCallback <Function> For TLS-PSK negotiation, see Pre-shared keys.

    • pskIdentityHint <string> 发送给客户端的可选提示,以帮助在 TLS-PSK 协商期间选择身份。在 TLS 1.3 中将被忽略。如果设置 pskIdentityHint 失败,将触发 'tlsClientError''ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' 代码。

      ¥pskIdentityHint <string> optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint 'tlsClientError' will be emitted with 'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' code.

    • ...:可以提供任何 tls.createSecureContext() 选项。对于服务器,通常需要标识选项(pfxkey/certpskCallback)。

      ¥...: Any tls.createSecureContext() option can be provided. For servers, the identity options (pfx, key/cert, or pskCallback) are usually required.

    • ...:可以提供任何 net.createServer() 选项。

      ¥...: Any net.createServer() option can be provided.

  • secureConnectionListener <Function>

  • 返回:<tls.Server>

    ¥Returns: <tls.Server>

创建新的 tls.ServersecureConnectionListener,如果提供,将自动设置为 'secureConnection' 事件的监听器。

¥Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the 'secureConnection' event.

ticketKeys 选项在 node:cluster 模块工作器之间自动共享。

¥The ticketKeys options is automatically shared between node:cluster module workers.

以下说明了一个简单的回显服务器:

¥The following illustrates a simple echo server:

const tls = require('node:tls');
const fs = require('node:fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using client certificate authentication.
  requestCert: true,

  // This is necessary only if the client uses a self-signed certificate.
  ca: [ fs.readFileSync('client-cert.pem') ],
};

const server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
}); 

可以通过使用 tls.connect() 的示例客户端连接到服务器来测试服务器。

¥The server can be tested by connecting to it using the example client from tls.connect().