tls.connect(options[, callback])


  • options <Object>

    • enableTrace:参见 tls.createServer()

      ¥enableTrace: See tls.createServer()

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

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

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

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

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

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

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

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

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

      ¥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> 对于 TLS-PSK 协商,请参阅 预共享密钥

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

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

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

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

      ¥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> Buffer 实例,包含 TLS 会话。

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

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

      ¥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> 与可读流 highWaterMark 参数一致。默认值:16 * 1024

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

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

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

      ¥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.

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

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

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

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

  • callback <Function>

  • 返回:<tls.TLSSocket>

    ¥Returns: <tls.TLSSocket>

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

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

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

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

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

¥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.

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

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

// Assumes an echo server that is listening on port 8000.
import { connect } from 'node:tls';
import { readFileSync } from 'node:fs';
import { stdin } from 'node:process';

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

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

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

const socket = connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  stdin.pipe(socket);
  stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  console.log('server ends connection');
});// Assumes an echo server that is listening on port 8000.
const { connect } = require('node:tls');
const { readFileSync } = require('node:fs');

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

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

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

const socket = 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');
});

要为此示例生成证书和密钥,则运行:

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

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

然后,要为此示例生成 server-cert.pem 证书,请运行:

¥Then, to generate the server-cert.pem certificate for this example, run:

openssl pkcs12 -certpbe AES-256-CBC -export -out server-cert.pem \
  -inkey client-key.pem -in client-cert.pem