tls.connect(options[, callback])
options
<Object>enableTrace
: 参见tls.createServer()
host
<string> 客户端应该连接到的主机。 默认值:'localhost'
。port
<number> 客户端应该连接到的端口。path
<string> 创建到路径的 Unix 套接字连接。 如果指定了此选项,则host
和port
将被忽略。socket
<stream.Duplex> 在给定的套接字上建立安全连接而不是创建新的套接字。 通常,这是net.Socket
的实例,但允许任何Duplex
流。 如果指定了此选项,则path
、host
和port
将被忽略,除了证书验证。 通常,套接字在传给tls.connect()
的时候就已经连接上了,但是可以稍后再连接。socket
的连接/断开/销毁是用户的责任;调用tls.connect()
不会导致调用net.connect()
。allowHalfOpen
<boolean> 详见net.Socket
的allowHalfOpen
选项。 默认值: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(预共享密钥)时,此函数将使用服务器提供的可选标识hint
或null
调用,以防 TLS 1.3 中删除了hint
。 有必要为连接提供自定义tls.checkServerIdentity()
,因为默认情况下会尝试根据证书检查服务器的主机名/IP,但这不适用于 PSK,因为不会存在证书。 可以在 RFC 4279 中找到更多信息。
- 提示:从服务器发送的 <string> 可选消息,以帮助客户端决定在协商期间使用哪个身份。
如果使用 TLS 1.3,则始终为
ALPNProtocols
: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 字符串数组、Buffer
、或TypedArray
、或DataView
、或包含支持的 ALPN 协议的单个Buffer
或TypedArray
或DataView
。Buffer
的格式应该是[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>。 如果验证了servername
和cert
,则该方法应该返回undefined
。session
<Buffer>Buffer
实例,包含 TLS 会话。minDHSize
<number> 接受 TLS 连接的 DH 参数的最小大小(以位为单位)。 当服务器提供大小小于minDHSize
的 DH 参数时,则 TLS 连接被销毁并抛出错误。 默认值:1024
。secureContext
: 使用tls.createSecureContext()
创建的 TLS 上下文对象。 如果secureContext
未提供,则将通过将整个options
对象传给tls.createSecureContext()
来创建。- ...: 如果缺少
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('tls');
const fs = require('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
: Seetls.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
andport
are ignored.socket
<stream.Duplex> Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance ofnet.Socket
, but anyDuplex
stream is allowed. If this option is specified,path
,host
andport
are ignored, except for certificate validation. Usually, a socket is already connected when passed totls.connect()
, but it can be connected later. Connection/disconnection/destruction ofsocket
is the user's responsibility; callingtls.connect()
will not causenet.connect()
to be called.allowHalfOpen
<boolean> If thesocket
option is missing, indicates whether or not to allow the internally created socket to be half-open, otherwise the option is ignored. See theallowHalfOpen
option ofnet.Socket
for details. Default:false
.rejectUnauthorized
<boolean> If notfalse
, 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> }
ornull
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 identityhint
provided by the server ornull
in case of TLS 1.3 wherehint
was removed. It will be necessary to provide a customtls.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.
- hint: <string> optional message sent from the server to help client
decide which identity to use during negotiation.
Always
ALPNProtocols
: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> An array of strings,Buffer
s orTypedArray
s orDataView
s, or a singleBuffer
orTypedArray
orDataView
containing the supported ALPN protocols.Buffer
s should have the format[len][name][len][name]...
e.g.'\x08http/1.1\x08http/1.0'
, where thelen
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 theSNICallback
option totls.createServer()
.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 providedservername
when explicitly set) against the certificate. This should return an <Error> if verification fails. The method should returnundefined
if theservername
andcert
are verified.session
<Buffer> ABuffer
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 thanminDHSize
, the TLS connection is destroyed and an error is thrown. Default:1024
.secureContext
: TLS context object created withtls.createSecureContext()
. If asecureContext
is not provided, one will be created by passing the entireoptions
object totls.createSecureContext()
.- ...:
tls.createSecureContext()
options that are used if thesecureContext
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('tls');
const fs = require('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');
});