tls.connect(options[, callback])
-
options<Object>-
enableTrace:参见tls.createServer()¥
enableTrace: Seetls.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 套接字连接。如果指定了此选项,则host和port将被忽略。¥
path<string> Creates Unix socket connection to path. If this option is specified,hostandportare ignored. -
socket<stream.Duplex> 在给定的套接字上建立安全连接而不是创建新的套接字。通常,这是net.Socket的实例,但允许任何Duplex流。如果指定此选项,则忽略path、host和port,证书验证除外。通常,套接字在传给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 ofnet.Socket, but anyDuplexstream is allowed. If this option is specified,path,host, andportare ignored, except for certificate validation. Usually, a socket is already connected when passed totls.connect(), but it can be connected later. Connection/disconnection/destruction ofsocketis the user's responsibility; callingtls.connect()will not causenet.connect()to be called. -
allowHalfOpen<boolean> 如果设置为false,则当可读端结束时,套接字将自动结束可写端。如果设置了socket选项,则该选项无效。详见net.Socket的allowHalfOpen选项。默认值:false。¥
allowHalfOpen<boolean> If set tofalse, then the socket will automatically end the writable side when the readable side ends. If thesocketoption is set, this option has no effect. See theallowHalfOpenoption ofnet.Socketfor details. Default:false. -
rejectUnauthorized<boolean> 如果不是false,则服务器证书将根据提供的 CA 列表进行验证。如果验证失败,则触发'error'事件;err.code包含 OpenSSL 错误代码。默认值:true。¥
rejectUnauthorized<boolean> If notfalse, the server certificate is verified against the list of supplied CAs. An'error'event is emitted if verification fails;err.codecontains 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 协议的字符串数组Buffer、TypedArray或DataView,或单个Buffer、TypedArray或DataView。Buffer应采用[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, orDataViews, or a singleBuffer,TypedArray, orDataViewcontaining the supported ALPN protocols.Buffers should have the format[len][name][len][name]...e.g.'\x08http/1.1\x08http/1.0', where thelenbyte 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 theSNICallbackoption totls.createServer(). -
checkServerIdentity(servername, cert)<Function> 根据证书检查服务器的主机名(或显式设置时提供的servername)时要使用的回调函数(而不是内置的tls.checkServerIdentity()函数)。如果验证失败,则这应该返回 <Error>。如果验证了servername和cert,则该方法应该返回undefined。¥
checkServerIdentity(servername, cert)<Function> A callback function to be used (instead of the builtintls.checkServerIdentity()function) when checking the server's host name (or the providedservernamewhen explicitly set) against the certificate. This should return an <Error> if verification fails. The method should returnundefinedif theservernameandcertare verified. -
session<Buffer>Buffer实例,包含 TLS 会话。¥
session<Buffer> ABufferinstance, 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 thanminDHSize, the TLS connection is destroyed and an error is thrown. Default:1024. -
highWaterMark:<number> 与可读流highWaterMark参数一致。默认值:16 * 1024。¥
highWaterMark: <number> Consistent with the readable streamhighWaterMarkparameter. Default:16 * 1024. -
secureContext:使用tls.createSecureContext()创建的 TLS 上下文对象。如果未提供secureContext,则会通过将整个options对象传递给tls.createSecureContext()来创建一个。¥
secureContext: TLS context object created withtls.createSecureContext(). If asecureContextis not provided, one will be created by passing the entireoptionsobject totls.createSecureContext(). -
onread<Object> 如果缺少socket选项,则传入的数据将存储在单个buffer中,并在数据到达套接字时传递给提供的callback,否则该选项将被忽略。详见net.Socket的onread选项。¥
onread<Object> If thesocketoption is missing, incoming data is stored in a singlebufferand passed to the suppliedcallbackwhen data arrives on the socket, otherwise the option is ignored. See theonreadoption ofnet.Socketfor details. -
...:如果缺少
secureContext选项,则使用tls.createSecureContext()选项,否则将忽略它们。¥...:
tls.createSecureContext()options that are used if thesecureContextoption is missing, otherwise they are ignored. -
...:任何尚未列出的
socket.connect()选项。¥...: Any
socket.connect()option not already listed.
-
-
callback<Function> -
¥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