tls.connect(options[, callback])


  • options <Object>
    • enableTrace: 参见 tls.createServer()

    • host <string> 客户端应该连接到的主机。 默认值: 'localhost'

    • port <number> 客户端应该连接到的端口。

    • path <string> 创建到路径的 Unix 套接字连接。 如果指定了此选项,则 hostport 将被忽略。

    • socket <stream.Duplex> 在给定的套接字上建立安全连接而不是创建新的套接字。 通常,这是 net.Socket 的实例,但允许任何 Duplex 流。 如果指定此选项,则忽略 pathhostport,证书验证除外。 通常,套接字在传给 tls.connect() 的时候就已经连接上了,但是可以稍后再连接。 socket 的连接/断开/销毁是用户的责任;调用 tls.connect() 不会导致调用 net.connect()

    • allowHalfOpen <boolean> 如果设置为 false,则当可读端结束时,套接字将自动结束可写端。 如果设置了 socket 选项,则该选项无效。 详见 net.SocketallowHalfOpen 选项。 默认值: false

    • rejectUnauthorized <boolean> 如果不是 false,则服务器证书将根据提供的 CA 列表进行验证。 如果验证失败,则会触发 'error' 事件;err.code 包含 OpenSSL 错误代码。 默认值: true

    • pskCallback <Function>

      • 提示:从服务器发送的 <string> 可选消息,以帮助客户端决定在协商期间使用哪个身份。 如果使用 TLS 1.3,则始终为 null
      • 返回: <Object>{ psk: <Buffer|TypedArray|DataView>, identity: <string> }null 形式停止协商过程。 psk 必须与所选密码的摘要兼容。 identity 必须使用 UTF-8 编码。

      当协商 TLS-PSK(预共享密钥)时,此函数将使用服务器提供的可选标识 hintnull 调用,以防 TLS 1.3 中删除了 hint。 有必要为连接提供自定义 tls.checkServerIdentity(),因为默认情况下会尝试根据证书检查服务器的主机名/IP,但这不适用于 PSK,因为不会存在证书。 可以在 RFC 4279 中找到更多信息。

    • ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 字符串数组,BufferTypedArrayDataView,或包含支持的 ALPN 协议的单个 BufferTypedArrayDataViewBuffer 的格式应该是 [len][name][len][name]...,例如 '\x08http/1.1\x08http/1.0',其中 len 字节是下一个协议名称的长度。 传入数组通常要简单得多,例如 ['http/1.1', 'http/1.0']。 列表中较早的协议比后面的有更高的优先级。

    • servername: <string> SNI(服务器名称指示)TLS 扩展的服务器名称。 它是所连接主机的名称,必须是主机名,而不是 IP 地址。 它可以被多宿主服务器用来选择正确的证书呈现给客户端,参见 SNICallback 选项到 tls.createServer()

    • checkServerIdentity(servername, cert) <Function> 根据证书检查服务器的主机名(或显式设置时提供的 servername)时要使用的回调函数(而不是内置的 tls.checkServerIdentity() 函数)。 如果验证失败,则这应该返回 <Error>。 如果验证了 servernamecert,则该方法应该返回 undefined

    • session <Buffer> Buffer 实例,包含 TLS 会话。

    • minDHSize <number> 接受 TLS 连接的 DH 参数的最小大小(以位为单位)。 当服务器提供大小小于 minDHSize 的 DH 参数时,则 TLS 连接被销毁并抛出错误。 默认值: 1024

    • highWaterMark: <number> 与可读流 highWaterMark 参数一致。 默认值: 16 * 1024

    • secureContext: 使用 tls.createSecureContext() 创建的 TLS 上下文对象。 如果 secureContext 未提供,则将通过将整个 options 对象传给 tls.createSecureContext() 来创建。

    • onread <Object> 如果缺少 socket 选项,则传入的数据将存储在单个 buffer 中,并在数据到达套接字时传递给提供的 callback,否则该选项将被忽略。 详见 net.Socketonread 选项。

    • ...: 如果缺少 secureContext 选项,则使用 tls.createSecureContext() 选项,否则它们将被忽略。

    • ...: 尚未列出的任何 socket.connect() 选项。

  • callback <Function>
  • 返回: <tls.TLSSocket>

callback 函数,如果指定,则将被添加为 'secureConnect' 事件的监听器。

tls.connect() 返回 tls.TLSSocket 对象。

https API不同,tls.connect() 默认不启用 SNI(服务器名称指示)扩展,这可能会导致部分服务器返回错误证书或完全拒绝连接。 要启用 SNI,除了 host 之外,还要设置 servername 选项。

以下说明了来自 tls.createServer() 的回显服务器示例的客户端:

// 假设回显服务器正在监听端口 8000。
const tls = require('node:tls');
const fs = require('node:fs');

const options = {
  // 仅当服务器需要客户端证书身份验证时才需要。
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // 仅当服务器使用自签名证书时才需要。
  ca: [ fs.readFileSync('server-cert.pem') ],

  // 仅当服务器的证书不适用于 "localhost" 时才需要。
  checkServerIdentity: () => { return null; },
};

const socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  console.log('server ends connection');
});
  • options <Object>
    • enableTrace: See tls.createServer()

    • host <string> Host the client should connect to. Default: 'localhost'.

    • port <number> Port the client should connect to.

    • path <string> Creates Unix socket connection to path. If this option is specified, host and port are ignored.

    • socket <stream.Duplex> Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of net.Socket, but any Duplex stream is allowed. If this option is specified, path, host, and port are ignored, except for certificate validation. Usually, a socket is already connected when passed to tls.connect(), but it can be connected later. Connection/disconnection/destruction of socket is the user's responsibility; calling tls.connect() will not cause net.connect() to be called.

    • allowHalfOpen <boolean> If set to false, then the socket will automatically end the writable side when the readable side ends. If the socket option is set, this option has no effect. See the allowHalfOpen option of net.Socket for details. Default: false.

    • rejectUnauthorized <boolean> If not false, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails; err.code contains the OpenSSL error code. Default: true.

    • pskCallback <Function>

      • hint: <string> optional message sent from the server to help client decide which identity to use during negotiation. Always null if TLS 1.3 is used.
      • Returns: <Object> in the form { psk: <Buffer|TypedArray|DataView>, identity: <string> } or null to stop the negotiation process. psk must be compatible with the selected cipher's digest. identity must use UTF-8 encoding.

      When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity hint provided by the server or null in case of TLS 1.3 where hint was removed. It will be necessary to provide a custom tls.checkServerIdentity() for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the RFC 4279.

    • 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. '\x08http/1.1\x08http/1.0', where the len byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. ['http/1.1', 'http/1.0']. Protocols earlier in the list have higher preference than those later.

    • servername: <string> Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the SNICallback option to tls.createServer().

    • checkServerIdentity(servername, cert) <Function> A callback function to be used (instead of the builtin tls.checkServerIdentity() function) when checking the server's host name (or the provided servername when explicitly set) against the certificate. This should return an <Error> if verification fails. The method should return undefined if the servername and cert are verified.

    • session <Buffer> A Buffer instance, containing TLS session.

    • minDHSize <number> Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than minDHSize, the TLS connection is destroyed and an error is thrown. Default: 1024.

    • highWaterMark: <number> Consistent with the readable stream highWaterMark parameter. Default: 16 * 1024.

    • secureContext: TLS context object created with tls.createSecureContext(). If a secureContext is not provided, one will be created by passing the entire options object to tls.createSecureContext().

    • onread <Object> If the socket option is missing, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket, otherwise the option is ignored. See the onread option of net.Socket for details.

    • ...: tls.createSecureContext() options that are used if the secureContext option is missing, otherwise they are ignored.

    • ...: Any socket.connect() option not already listed.

  • callback <Function>
  • Returns: <tls.TLSSocket>

The callback function, if specified, will be added as a listener for the 'secureConnect' event.

tls.connect() returns a tls.TLSSocket object.

Unlike the https API, tls.connect() does not enable the SNI (Server Name Indication) extension by default, which may cause some servers to return an incorrect certificate or reject the connection altogether. To enable SNI, set the servername option in addition to host.

The following illustrates a client for the echo server example from tls.createServer():

// Assumes an echo server that is listening on port 8000.
const tls = require('node:tls');
const fs = require('node:fs');

const options = {
  // Necessary only if the server requires client certificate authentication.
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // Necessary only if the server uses a self-signed certificate.
  ca: [ fs.readFileSync('server-cert.pem') ],

  // Necessary only if the server's cert isn't for "localhost".
  checkServerIdentity: () => { return null; },
};

const socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  console.log('server ends connection');
});