socket.connect(options[, connectListener])
options
<Object>connectListener
<Function>socket.connect()
方法的常用参数。 将被添加为'connect'
事件的监听器一次。- 返回: <net.Socket> 套接字自身
在给定的套接字上发起连接。
一般不需要这个方法,套接字应该用 net.createConnection()
创建和打开。
仅在实现自定义套接字时使用它。
对于 TCP 连接,可用的 options
是:
port
<number> 必需的。 套接字应连接到的端口。host
<string> 套接字应连接到的主机。 默认值:'localhost'
。localAddress
<string> 套接字应该连接的本地地址。localPort
<number> 套接字应连接的本地端口。family
<number>: IP 堆栈的版本。 必须是4
、6
或0
。 值0
表示允许 IPv4 和 IPv6 地址。 默认值:0
。hints
<number> 可选的dns.lookup()
提示。lookup
<Function> 自定义查找函数。 默认值:dns.lookup()
.noDelay
<boolean> 如果设置为true
,则它会在套接字建立后立即禁用 Nagle 算法。 默认值:false
。keepAlive
<boolean> 如果设置为true
,则它会在连接建立后立即在套接字上启用保持活动功能,类似于在socket.setKeepAlive([enable][, initialDelay])
中所做的。 默认值:false
。keepAliveInitialDelay
<number> 如果设置为正数,则它会设置在空闲套接字上发送第一个保持活跃探测之前的初始延迟。默认值:0
。autoSelectFamily
<boolean>: 如果设置为true
,它会启用一个族自动检测算法,该算法松散地实现 RFC 8305 的第 5 节。 传递给 lookup 的all
选项设置为true
,套接字会依次尝试连接到所有获得的 IPv6 和 IPv4 地址,直到建立连接。 首先尝试返回的 AAAA 地址,然后尝试返回的 A 地址,以此类推。 在超时和尝试下一个地址之前,每个连接尝试都被赋予autoSelectFamilyAttemptTimeout
选项指定的时间量。 如果family
选项不是0
或设置了localAddress
,则忽略。 如果至少有一个连接成功,则不会发出连接错误。 默认值:false
。autoSelectFamilyAttemptTimeout
<number>: 使用autoSelectFamily
选项时,在尝试下一个地址之前等待连接尝试完成的时间(以毫秒为单位)。 如果设置为小于10
的正整数,则将使用值10
。 默认值:250
。
对于 IPC 连接,可用的 options
是:
path
<string> 必需的。 客户端应该连接到的路径。 请参阅标识 IPC 连接的路径。 如果提供,则忽略上面特定于 TCP 的选项。
对于这两种类型,可用的 options
包括:
onread
<Object> 如果指定,传入的数据存储在单个buffer
中,并在数据到达套接字时传给提供的callback
。 这将导致流功能不提供任何数据。 套接字将像往常一样触发'error'
、'end'
和'close'
等事件。pause()
和resume()
等方法也将按预期运行。buffer
<Buffer> | <Uint8Array> | <Function> 用于存储传入数据的可重用内存块或返回此类数据的函数。callback
<Function> 为每个传入数据块调用此函数。 传给它的有两个参数:写入buffer
的字节数和对buffer
的引用。 从此函数返回false
以隐式pause()
套接字。 该函数将在全局上下文中执行。
以下是使用 onread
选项的客户端示例:
const net = require('node:net');
net.connect({
port: 80,
onread: {
// 每次从套接字读取时重用 4KiB 缓冲区。
buffer: Buffer.alloc(4 * 1024),
callback: function(nread, buf) {
// 接收到的数据在 `buf` 中可用,从 0 到 `nread`。
console.log(buf.toString('utf8', 0, nread));
},
},
});
options
<Object>connectListener
<Function> Common parameter ofsocket.connect()
methods. Will be added as a listener for the'connect'
event once.- Returns: <net.Socket> The socket itself.
Initiate a connection on a given socket. Normally this method is not needed,
the socket should be created and opened with net.createConnection()
. Use
this only when implementing a custom Socket.
For TCP connections, available options
are:
port
<number> Required. Port the socket should connect to.host
<string> Host the socket should connect to. Default:'localhost'
.localAddress
<string> Local address the socket should connect from.localPort
<number> Local port the socket should connect from.family
<number>: Version of IP stack. Must be4
,6
, or0
. The value0
indicates that both IPv4 and IPv6 addresses are allowed. Default:0
.hints
<number> Optionaldns.lookup()
hints.lookup
<Function> Custom lookup function. Default:dns.lookup()
.noDelay
<boolean> If set totrue
, it disables the use of Nagle's algorithm immediately after the socket is established. Default:false
.keepAlive
<boolean> If set totrue
, it enables keep-alive functionality on the socket immediately after the connection is established, similarly on what is done insocket.setKeepAlive([enable][, initialDelay])
. Default:false
.keepAliveInitialDelay
<number> If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket.Default:0
.autoSelectFamily
<boolean>: If set totrue
, it enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. Theall
option passed to lookup is set totrue
and the sockets attempts to connect to all obtained IPv6 and IPv4 addresses, in sequence, until a connection is established. The first returned AAAA address is tried first, then the first returned A address and so on. Each connection attempt is given the amount of time specified by theautoSelectFamilyAttemptTimeout
option before timing out and trying the next address. Ignored if thefamily
option is not0
or iflocalAddress
is set. Connection errors are not emitted if at least one connection succeeds. Default:false
.autoSelectFamilyAttemptTimeout
<number>: The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using theautoSelectFamily
option. If set to a positive integer less than10
, then the value10
will be used instead. Default:250
.
For IPC connections, available options
are:
path
<string> Required. Path the client should connect to. See Identifying paths for IPC connections. If provided, the TCP-specific options above are ignored.
For both types, available options
include:
onread
<Object> If specified, incoming data is stored in a singlebuffer
and passed to the suppliedcallback
when data arrives on the socket. This will cause the streaming functionality to not provide any data. The socket will emit events like'error'
,'end'
, and'close'
as usual. Methods likepause()
andresume()
will also behave as expected.buffer
<Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to use for storing incoming data or a function that returns such.callback
<Function> This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written tobuffer
and a reference tobuffer
. Returnfalse
from this function to implicitlypause()
the socket. This function will be executed in the global context.
Following is an example of a client using the onread
option:
const net = require('node:net');
net.connect({
port: 80,
onread: {
// Reuses a 4KiB Buffer for every read from the socket.
buffer: Buffer.alloc(4 * 1024),
callback: function(nread, buf) {
// Received data is available in `buf` from 0 to `nread`.
console.log(buf.toString('utf8', 0, nread));
},
},
});