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> 有关 TLS-PSK 协商,请参阅 预共享密钥
    • 'ALPNProtocols' <string[]> | <TypedArray[]> | <DataView[]> | <TypedArray> | <DataView> 一组字符串,'Buffer's、'TypedArray's、'DataView's,或单个包含支持ALPN协议的'Buffer'、'TypedArray'或'DataView'。'缓冲区'的格式应为'[长度][name][长度][name]...',例如'\x08http/1.1\x08http/1.0'',其中'len'字节是下一个协议名称的长度。传递数组通常要简单得多,例如: '['http/1.1', 'http/1.0']''.列表较早的协议优先级高于后面的方案。
    • servername <string> SNI(服务器名称指示)TLS 扩展的服务器名称。它是正在连接的主机名称,必须是主机名,而不能是 IP 地址。多网卡服务器可以使用它来选择向客户端呈现的正确证书,请参阅 tls.createServer()SNICallback 选项。
    • checkServerIdentity(servername, cert) <Function> 一个回调函数,用于在检查服务器的主机名(或在显式设置时提供的 servername)与证书匹配时使用(替代内置的 tls.checkServerIdentity() 函数)。如果验证失败,应返回 <Error>。如果 servernamecert 验证成功,应返回 undefined
    • session <Buffer> 一个 Buffer 实例,包含 TLS 会话。
    • minDHSize <number> 接受 TLS 连接的 DH 参数最小大小(以位为单位)。当服务器提供的 DH 参数大小小于 minDHSize 时,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' 事件的监听器。

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

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

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