- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS模块
- module/esm ECMAScript模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v20.10.0 文档
- Node.js v20.10.0
-
►
目录
- 网络
- IPC 支持
- 类:
net.BlockList
- 类:
net.SocketAddress
- 类:
net.Server
- 类:
net.Socket
new net.Socket([options])
- 事件:
'close'
- 事件:
'connect'
- 事件:
'data'
- 事件:
'drain'
- 事件:
'end'
- 事件:
'error'
- 事件:
'lookup'
- 事件:
'ready'
- 事件:
'timeout'
socket.address()
socket.autoSelectFamilyAttemptedAddresses
socket.bufferSize
socket.bytesRead
socket.bytesWritten
socket.connect()
socket.connecting
socket.destroy([error])
socket.destroyed
socket.destroySoon()
socket.end([data[, encoding]][, callback])
socket.localAddress
socket.localPort
socket.localFamily
socket.pause()
socket.pending
socket.ref()
socket.remoteAddress
socket.remoteFamily
socket.remotePort
socket.resetAndDestroy()
socket.resume()
socket.setEncoding([encoding])
socket.setKeepAlive([enable][, initialDelay])
socket.setNoDelay([noDelay])
socket.setTimeout(timeout[, callback])
socket.timeout
socket.unref()
socket.write(data[, encoding][, callback])
socket.readyState
net.connect()
net.createConnection()
net.createServer([options][, connectionListener])
net.getDefaultAutoSelectFamily()
net.setDefaultAutoSelectFamily(value)
net.getDefaultAutoSelectFamilyAttemptTimeout()
net.setDefaultAutoSelectFamilyAttemptTimeout(value)
net.isIP(input)
net.isIPv4(input)
net.isIPv6(input)
- 网络
-
►
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS模块
- module/esm ECMAScript模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- ► 其他版本
网络#
源代码: lib/net.js
node:net
模块提供异步网络 API,用于创建基于流的 TCP 或 IPC 服务器 (net.createServer()
) 和客户端 (net.createConnection()
)。
英The node:net
module provides an asynchronous network API for creating stream-based
TCP or IPC servers (net.createServer()
) and clients
(net.createConnection()
).
可以使用以下方式访问它:
英It can be accessed using:
const net = require('node:net');
IPC 支持#
node:net
模块在 Windows 上使用命名管道支持 IPC,在其他操作系统上则使用 Unix 域套接字。
英The node:net
module supports IPC with named pipes on Windows, and Unix domain
sockets on other operating systems.
识别 IPC 连接的路径#
net.connect()
、net.createConnection()
、server.listen()
、socket.connect()
采用 path
参数标识 IPC 端点。
英net.connect()
, net.createConnection()
, server.listen()
, and
socket.connect()
take a path
parameter to identify IPC endpoints.
在 Unix 上,本地域也称为 Unix 域。 路径是文件系统路径名。 它被截断为与操作系统相关的 sizeof(sockaddr_un.sun_path) - 1
长度。 典型的值为 Linux 上的 107 字节和 macOS 上的 103 字节。 如果 Node.js API 抽象创建了 Unix 域套接字,则它也会取消链接 Unix 域套接字。 例如,net.createServer()
可以会创建 Unix 域套接字,而 server.close()
将取消链接它。 但是如果用户在这些抽象之外创建了 Unix 域套接字,则用户将需要删除它。 这同样适用于 Node.js API 创建 Unix 域套接字但程序随后崩溃的情况。 简而言之,Unix 域套接字将在文件系统中可见,并且会一直存在直到取消链接。
英On Unix, the local domain is also known as the Unix domain. The path is a
file system pathname. It gets truncated to an OS-dependent length of
sizeof(sockaddr_un.sun_path) - 1
. Typical values are 107 bytes on Linux and
103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,
it will unlink the Unix domain socket as well. For example,
net.createServer()
may create a Unix domain socket and
server.close()
will unlink it. But if a user creates the Unix domain
socket outside of these abstractions, the user will need to remove it. The same
applies when a Node.js API creates a Unix domain socket but the program then
crashes. In short, a Unix domain socket will be visible in the file system and
will persist until unlinked.
在 Windows 上,本地域是使用命名管道实现的。 该路径必须引用 \\?\pipe\
或 \\.\pipe\
中的条目。 允许使用任何字符,但后者可能会对管道名称进行一些处理,例如解析 ..
序列。 不管它看起来如何,管道命名空间是扁平的。 管道不会持续存在。 当对它们的最后一个引用关闭时,它们将被删除。
与 Unix 域套接字不同,Windows 将在拥有进程退出时关闭并删除管道。
英On Windows, the local domain is implemented using a named pipe. The path must
refer to an entry in \\?\pipe\
or \\.\pipe\
. Any characters are permitted,
but the latter may do some processing of pipe names, such as resolving ..
sequences. Despite how it might look, the pipe namespace is flat. Pipes will
not persist. They are removed when the last reference to them is closed.
Unlike Unix domain sockets, Windows will close and remove the pipe when the
owning process exits.
JavaScript 字符串转义需要使用额外的反斜杠转义来指定路径,例如:
英JavaScript string escaping requires paths to be specified with extra backslash escaping such as:
net.createServer().listen(
path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
类:net.BlockList
#
BlockList
对象可与一些网络 API 一起使用,以指定用于禁用对特定 IP 地址、IP 范围或 IP 子网的入站或出站访问的规则。
英The BlockList
object can be used with some network APIs to specify rules for
disabling inbound or outbound access to specific IP addresses, IP ranges, or
IP subnets.
blockList.addAddress(address[, type])
#
address
<string> | <net.SocketAddress> IPv4 或 IPv6 地址。type
<string>'ipv4'
或'ipv6'
。 默认值:'ipv4'
。
添加规则以阻止给定的 IP 地址。
英Adds a rule to block the given IP address.
blockList.addRange(start, end[, type])
#
start
<string> | <net.SocketAddress> 范围内的起始 IPv4 或 IPv6 地址。end
<string> | <net.SocketAddress> 范围内的结束 IPv4 或 IPv6 地址。type
<string>'ipv4'
或'ipv6'
。 默认值:'ipv4'
。
添加规则以阻止从 start
(包含)到 end
(包含)的 IP 地址范围。
英Adds a rule to block a range of IP addresses from start
(inclusive) to
end
(inclusive).
blockList.addSubnet(net, prefix[, type])
#
net
<string> | <net.SocketAddress> 网络 IPv4 或 IPv6 地址。prefix
<number> CIDR 前缀位数。 对于 IPv4,这必须是0
和32
之间的值。 对于 IPv6,它必须在0
和128
之间。type
<string>'ipv4'
或'ipv6'
。 默认值:'ipv4'
。
添加规则以阻止指定为子网掩码的 IP 地址范围。
英Adds a rule to block a range of IP addresses specified as a subnet mask.
blockList.check(address[, type])
#
address
<string> | <net.SocketAddress> 要检查的 IP 地址type
<string>'ipv4'
或'ipv6'
。 默认值:'ipv4'
。- 返回: <boolean>
如果给定的 IP 地址与添加到 BlockList
的任何规则匹配,则返回 true
。
英Returns true
if the given IP address matches any of the rules added to the
BlockList
.
const blockList = new net.BlockList();
blockList.addAddress('123.123.123.123');
blockList.addRange('10.0.0.1', '10.0.0.10');
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
console.log(blockList.check('123.123.123.123')); // Prints: true
console.log(blockList.check('10.0.0.3')); // Prints: true
console.log(blockList.check('222.111.111.222')); // Prints: false
// IPv6 notation for IPv4 addresses works:
console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
blockList.rules
#
- 类型: <string[]>
添加到阻止列表的规则列表。
英The list of rules added to the blocklist.
类:net.SocketAddress
#
new net.SocketAddress([options])
#
options
<Object>
socketaddress.address
#
- 类型 <string>
socketaddress.family
#
- 类型 <string>
'ipv4'
或'ipv6'
。
socketaddress.flowlabel
#
- 类型 <number>
socketaddress.port
#
- 类型 <number>
类:net.Server
#
- 继承: <EventEmitter>
此类用于创建 TCP 或 IPC 服务器。
英This class is used to create a TCP or IPC server.
new net.Server([options][, connectionListener])
#
options
<Object> 参见net.createServer([options][, connectionListener])
。connectionListener
<Function> 自动设置为'connection'
事件的监听器。- 返回: <net.Server>
net.Server
是具有以下事件的 EventEmitter
:
英net.Server
is an EventEmitter
with the following events:
事件:'close'
#
服务器关闭时触发。 如果连接存在,则在所有连接结束之前不会触发此事件。
英Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.
事件:'connection'
#
- <net.Socket> 连接对象
建立新连接时触发。 socket
是 net.Socket
的实例。
英Emitted when a new connection is made. socket
is an instance of
net.Socket
.
事件:'error'
#
发生错误时触发。 与 net.Socket
不同,除非手动调用 server.close()
,否则 'close'
事件将在此事件之后直接触发 not。 参见 server.listen()
讨论中的示例。
英Emitted when an error occurs. Unlike net.Socket
, the 'close'
event will not be emitted directly following this event unless
server.close()
is manually called. See the example in discussion of
server.listen()
.
事件:'listening'
#
在调用 server.listen()
后绑定服务器时触发。
英Emitted when the server has been bound after calling server.listen()
.
事件:'drop'
#
当连接数达到 server.maxConnections
的阈值时,服务器将丢弃新的连接并触发 'drop'
事件。 如果是 TCP 服务器,参数如下,否则参数为 undefined
。
英When the number of connections reaches the threshold of server.maxConnections
,
the server will drop new connections and emit 'drop'
event instead. If it is a
TCP server, the argument is as follows, otherwise the argument is undefined
.
data
<Object> 传给事件监听器的参数。
server.address()
#
如果监听 IP 套接字,则返回操作系统报告的绑定 address
、地址 family
名称和服务器的 port
(在获取操作系统分配的地址时有助于查找分配的端口):
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
。
英Returns the bound address
, the address family
name, and port
of the server
as reported by the operating system if listening on an IP socket
(useful to find which port was assigned when getting an OS-assigned address):
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
.
对于监听管道或 Unix 域套接字的服务器,名称作为字符串返回。
英For a server listening on a pipe or Unix domain socket, the name is returned as a string.
const server = net.createServer((socket) => {
socket.end('goodbye\n');
}).on('error', (err) => {
// Handle errors here.
throw err;
});
// Grab an arbitrary unused port.
server.listen(() => {
console.log('opened server on', server.address());
});
server.address()
在 'listening'
事件触发之前或调用 server.close()
之后返回 null
。
英server.address()
returns null
before the 'listening'
event has been
emitted or after calling server.close()
.
server.close([callback])
#
callback
<Function> 服务器关闭时调用。- 返回: <net.Server>
停止服务器接受新连接并保持现有连接。 该函数是异步的,当所有连接都结束并且服务器触发 'close'
事件时,则服务器最终关闭。
一旦 'close'
事件发生,则可选的 callback
将被调用。 与该事件不同,如果服务器在关闭时未打开,它将以 Error
作为唯一参数被调用。
英Stops the server from accepting new connections and keeps existing
connections. This function is asynchronous, the server is finally closed
when all connections are ended and the server emits a 'close'
event.
The optional callback
will be called once the 'close'
event occurs. Unlike
that event, it will be called with an Error
as its only argument if the server
was not open when it was closed.
server[Symbol.asyncDispose]()
#
调用 server.close()
并返回一个在服务器关闭时履行的 promise。
英Calls server.close()
and returns a promise that fulfills when the
server has closed.
server.getConnections(callback)
#
callback
<Function>- 返回: <net.Server>
异步获取服务器上的并发连接数。 当套接字被发送到分叉时工作。
英Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.
回调应该采用两个参数 err
和 count
。
英Callback should take two arguments err
and count
.
server.listen()
#
启动监听连接的服务器。 net.Server
可以是 TCP 或 IPC 服务器,具体取决于它监听的内容。
英Start a server listening for connections. A net.Server
can be a TCP or
an IPC server depending on what it listens to.
可能的语法有:
英Possible signatures:
server.listen(handle[, backlog][, callback])
server.listen(options[, callback])
server.listen(path[, backlog][, callback])
用于 IPC 服务器server.listen([port[, host[, backlog]]][, callback])
用于 TCP 服务器
这个函数是异步的。 当服务器开始监听时,将触发 'listening'
事件。 最后一个参数 callback
将被添加为 'listening'
事件的监听器。
英This function is asynchronous. When the server starts listening, the
'listening'
event will be emitted. The last parameter callback
will be added as a listener for the 'listening'
event.
所有 listen()
方法都可以采用 backlog
参数来指定挂起连接队列的最大长度。 实际长度将由操作系统通过 sysctl 设置确定,例如 Linux 上的 tcp_max_syn_backlog
和 somaxconn
。 此参数的默认值为 511(而非 512)。
英All listen()
methods can take a backlog
parameter to specify the maximum
length of the queue of pending connections. The actual length will be determined
by the OS through sysctl settings such as tcp_max_syn_backlog
and somaxconn
on Linux. The default value of this parameter is 511 (not 512).
所有 net.Socket
都设置为 SO_REUSEADDR
(详见 socket(7)
)。
英All net.Socket
are set to SO_REUSEADDR
(see socket(7)
for
details).
当且仅当在第一次 server.listen()
调用期间出现错误或 server.close()
已被调用时,才能再次调用 server.listen()
方法。 否则,将抛出 ERR_SERVER_ALREADY_LISTEN
错误。
英The server.listen()
method can be called again if and only if there was an
error during the first server.listen()
call or server.close()
has been
called. Otherwise, an ERR_SERVER_ALREADY_LISTEN
error will be thrown.
收听时最常见的错误之一是 EADDRINUSE
。
当另一台服务器已经在监听请求的 port
/path
/handle
时,就会发生这种情况。 处理此问题的一种方法是在一定时间后重试:
英One of the most common errors raised when listening is EADDRINUSE
.
This happens when another server is already listening on the requested
port
/path
/handle
. One way to handle this would be to retry
after a certain amount of time:
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.error('Address in use, retrying...');
setTimeout(() => {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});
server.listen(handle[, backlog][, callback])
#
handle
<Object>backlog
<number>server.listen()
函数的通用参数callback
<Function>- 返回: <net.Server>
启动服务器监听给定 handle
上的连接,该 handle
已经绑定到端口、Unix 域套接字或 Windows 命名管道。
英Start a server listening for connections on a given handle
that has
already been bound to a port, a Unix domain socket, or a Windows named pipe.
handle
对象可以是服务器、套接字(任何具有底层 _handle
成员的对象)或具有 fd
成员(有效文件描述符)的对象。
英The handle
object can be either a server, a socket (anything with an
underlying _handle
member), or an object with an fd
member that is a
valid file descriptor.
Windows 不支持监听文件描述符。
英Listening on a file descriptor is not supported on Windows.
server.listen(options[, callback])
#
options
<Object> 必需的。 支持以下属性:port
<number>host
<string>path
<string> 如果指定了port
,则将被忽略。 参见 识别 IPC 连接的路径。backlog
<number>server.listen()
函数的通用参数。exclusive
<boolean> 默认值:false
readableAll
<boolean> 对于 IPC 服务器,使管道对所有用户都可读。 默认值:false
。writableAll
<boolean> 对于 IPC 服务器,使管道对所有用户都可写。 默认值:false
。ipv6Only
<boolean> 对于 TCP 服务器,将ipv6Only
设置为true
将禁用双栈支持,即绑定到主机::
不会绑定0.0.0.0
。 默认值:false
。signal
<AbortSignal> 可用于关闭监听服务器的中止信号。
callback
<Function> 函数。- 返回: <net.Server>
如果指定了 port
,则其行为与 server.listen([port[, host[, backlog]]][, callback])
相同。
否则,如果指定了 path
,则其行为与 server.listen(path[, backlog][, callback])
相同。
如果未指定它们,则会抛出错误。
英If port
is specified, it behaves the same as
server.listen([port[, host[, backlog]]][, callback])
.
Otherwise, if path
is specified, it behaves the same as
server.listen(path[, backlog][, callback])
.
If none of them is specified, an error will be thrown.
如果 exclusive
是 false
(默认值),那么集群工作者将使用相同的底层句柄,允许共享连接处理职责。 当 exclusive
为 true
时,句柄未共享,尝试端口共享会导致错误。 下面显示了一个监听独占端口的示例。
英If exclusive
is false
(default), then cluster workers will use the same
underlying handle, allowing connection handling duties to be shared. When
exclusive
is true
, the handle is not shared, and attempted port sharing
results in an error. An example which listens on an exclusive port is
shown below.
server.listen({
host: 'localhost',
port: 80,
exclusive: true,
});
当 exclusive
为 true
且底层 handle 共享时,有可能多个 worker 查询一个 handle 具有不同的积压。
在这种情况下,将使用传递给主进程的第一个 backlog
。
英When exclusive
is true
and the underlying handle is shared, it is
possible that several workers query a handle with different backlogs.
In this case, the first backlog
passed to the master process will be used.
以 root 身份启动 IPC 服务器可能会导致非特权用户无法访问服务器路径。 使用 readableAll
和 writableAll
将使所有用户都可以访问服务器。
英Starting an IPC server as root may cause the server path to be inaccessible for
unprivileged users. Using readableAll
and writableAll
will make the server
accessible for all users.
如果启用了 signal
选项,在对应的 AbortController
上调用 .abort()
类似于在服务器上调用 .close()
:
英If the signal
option is enabled, calling .abort()
on the corresponding
AbortController
is similar to calling .close()
on the server:
const controller = new AbortController();
server.listen({
host: 'localhost',
port: 80,
signal: controller.signal,
});
// Later, when you want to close the server.
controller.abort();
server.listen(path[, backlog][, callback])
#
path
<string> 服务器应该监听的路径。 参见 识别 IPC 连接的路径。backlog
<number>server.listen()
函数的通用参数。callback
<Function>。- 返回: <net.Server>
启动 IPC 服务器监听给定 path
上的连接。
英Start an IPC server listening for connections on the given path
.
server.listen([port[, host[, backlog]]][, callback])
#
port
<number>host
<string>backlog
<number>server.listen()
函数的通用参数。callback
<Function>。- 返回: <net.Server>
启动 TCP 服务器监听给定 port
和 host
上的连接。
英Start a TCP server listening for connections on the given port
and host
.
如果 port
被省略或为 0,操作系统将分配一个任意未使用的端口,可以在触发 'listening'
事件后使用 server.address().port
检索该端口。
英If port
is omitted or is 0, the operating system will assign an arbitrary
unused port, which can be retrieved by using server.address().port
after the 'listening'
event has been emitted.
如果省略 host
,服务器将在 IPv6 可用时接受 未指定的 IPv6 地址 (::
) 上的连接,否则接受 未指定的 IPv4 地址 (0.0.0.0
) 上的连接。
英If host
is omitted, the server will accept connections on the
unspecified IPv6 address (::
) when IPv6 is available, or the
unspecified IPv4 address (0.0.0.0
) otherwise.
在大多数操作系统中,监听 未指定的 IPv6 地址 (::
) 可能会导致 net.Server
也监听 未指定的 IPv4 地址 (0.0.0.0
)。
英In most operating systems, listening to the unspecified IPv6 address (::
)
may cause the net.Server
to also listen on the unspecified IPv4 address
(0.0.0.0
).
server.listening
#
- <boolean> 指示服务器是否正在监听连接。
server.maxConnections
#
设置此属性以在服务器的连接计数变高时拒绝连接。
英Set this property to reject connections when the server's connection count gets high.
一旦将套接字发送给具有 child_process.fork()
的子级,不建议使用此选项。
英It is not recommended to use this option once a socket has been sent to a child
with child_process.fork()
.
server.ref()
#
- 返回: <net.Server>
与 unref()
相反,如果它是唯一剩下的服务器(默认行为),则在以前的 unref
ed 服务器上调用 ref()
不会让程序退出。
如果服务器 ref
ed 再次调用 ref()
将无效。
英Opposite of unref()
, calling ref()
on a previously unref
ed server will
not let the program exit if it's the only server left (the default behavior).
If the server is ref
ed calling ref()
again will have no effect.
server.unref()
#
- 返回: <net.Server>
如果这是事件系统中唯一活动的服务器,则在服务器上调用 unref()
将允许程序退出。 如果服务器已经 unref
ed 再次调用 unref()
将无效。
英Calling unref()
on a server will allow the program to exit if this is the only
active server in the event system. If the server is already unref
ed calling
unref()
again will have no effect.
类:net.Socket
#
- 继承: <stream.Duplex>
此类是 TCP 套接字或流式 IPC 端点的抽象(在 Windows 上使用命名管道,否则使用 Unix 域套接字)。 它也是 EventEmitter
。
英This class is an abstraction of a TCP socket or a streaming IPC endpoint
(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
an EventEmitter
.
net.Socket
可以由用户创建并直接用于与服务器交互。 例如,它由 net.createConnection()
返回,因此用户可以使用它与服务器对话。
英A net.Socket
can be created by the user and used directly to interact with
a server. For example, it is returned by net.createConnection()
,
so the user can use it to talk to the server.
它也可以由 Node.js 创建并在收到连接时传递给用户。 例如,它被传递给 net.Server
上触发的 'connection'
事件的监听器,因此用户可以使用它与客户端进行交互。
英It can also be created by Node.js and passed to the user when a connection
is received. For example, it is passed to the listeners of a
'connection'
event emitted on a net.Server
, so the user can use
it to interact with the client.
new net.Socket([options])
#
options
<Object> 可用的选项有:fd
<number> 如果指定,则使用给定的文件描述符封装现有的套接字,否则将创建新的套接字。allowHalfOpen
<boolean> 如果设置为false
,则当可读端结束时,套接字将自动结束可写端。 有关详细信息,请参阅net.createServer()
和'end'
事件。 默认值:false
。readable
<boolean> 当传入fd
时,则允许在套接字上读取,否则将被忽略。 默认值:false
。writable
<boolean> 当传入fd
时,则允许在套接字上写入,否则将被忽略。 默认值:false
。signal
<AbortSignal> 可用于销毁套接字的中止信号。
- 返回: <net.Socket>
创建一个新的套接字对象。
英Creates a new socket object.
新创建的套接字可以是 TCP 套接字或流式 IPC 端点,具体取决于它 connect()
的用途。
英The newly created socket can be either a TCP socket or a streaming IPC
endpoint, depending on what it connect()
to.
事件:'close'
#
hadError
<boolean> 如果套接字有传输错误,则为true
。
套接字完全关闭后触发。 参数 hadError
是一个布尔值,表示套接字是否由于传输错误而关闭。
英Emitted once the socket is fully closed. The argument hadError
is a boolean
which says if the socket was closed due to a transmission error.
事件:'connect'
#
成功建立套接字连接时触发。
参见 net.createConnection()
。
英Emitted when a socket connection is successfully established.
See net.createConnection()
.
事件:'data'
#
收到数据时触发。 参数 data
将是 Buffer
或 String
。 数据编码由 socket.setEncoding()
设置。
英Emitted when data is received. The argument data
will be a Buffer
or
String
. Encoding of data is set by socket.setEncoding()
.
如果 Socket
触发 'data'
事件时没有监听器,则数据将丢失。
英The data will be lost if there is no listener when a Socket
emits a 'data'
event.
事件:'drain'
#
当写缓冲区变空时触发。 可用于限制上传。
英Emitted when the write buffer becomes empty. Can be used to throttle uploads.
也可以看看: socket.write()
的返回值。
英See also: the return values of socket.write()
.
事件:'end'
#
当套接字的另一端触发传输结束信号时触发,从而结束套接字的可读端。
英Emitted when the other end of the socket signals the end of transmission, thus ending the readable side of the socket.
默认情况下(allowHalfOpen
是 false
)套接字将发送回传输结束数据包并在写完其待处理的写入队列后销毁其文件描述符。 但是,如果 allowHalfOpen
设置为 true
,套接字将不会自动 end()
其可写端,允许用户写入任意数量的数据。 用户必须显式调用 end()
以关闭连接(即发回 FIN 数据包)。
英By default (allowHalfOpen
is false
) the socket will send an end of
transmission packet back and destroy its file descriptor once it has written out
its pending write queue. However, if allowHalfOpen
is set to true
, the
socket will not automatically end()
its writable side,
allowing the user to write arbitrary amounts of data. The user must call
end()
explicitly to close the connection (i.e. sending a
FIN packet back).
事件:'error'
#
发生错误时触发。 'close'
事件将在此事件之后直接调用。
英Emitted when an error occurs. The 'close'
event will be called directly
following this event.
事件:'lookup'
#
在解析主机名之后但在连接之前触发。 不适用于 Unix 套接字。
英Emitted after resolving the host name but before connecting. Not applicable to Unix sockets.
err
<Error> | <null> 错误对象。 参见dns.lookup()
。address
<string> IP 地址。family
<number> | <null> 地址类型。 参见dns.lookup()
。host
<string> 主机名。
事件:'ready'
#
当套接字准备好使用时触发。
英Emitted when a socket is ready to be used.
在 'connect'
之后立即触发。
英Triggered immediately after 'connect'
.
事件:'timeout'
#
如果套接字因不活动而超时则触发。 这只是为了通知套接字已经空闲。 用户必须手动关闭连接。
英Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.
也可以看看: socket.setTimeout()
。
英See also: socket.setTimeout()
.
socket.address()
#
- 返回: <Object>
返回操作系统报告的绑定 address
、地址 family
名称和套接字 port
:
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
英Returns the bound address
, the address family
name and port
of the
socket as reported by the operating system:
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
socket.autoSelectFamilyAttemptedAddresses
#
只有在 socket.connect(options)
中启用了系列自动选择算法并且它是已尝试的地址数组时,此属性才会存在。
英This property is only present if the family autoselection algorithm is enabled in
socket.connect(options)
and it is an array of the addresses that have been attempted.
每个地址都是 $IP:$PORT
形式的字符串。 如果连接成功,那么最后一个地址就是套接字当前连接到的地址。
英Each address is a string in the form of $IP:$PORT
. If the connection was successful,
then the last address is the one that the socket is currently connected to.
socket.bufferSize
#
writable.writableLength
。此属性显示为写入而缓冲的字符数。 缓冲区可能包含编码后长度未知的字符串。 所以这个数字只是缓冲区中字节数的近似值。
英This property shows the number of characters buffered for writing. The buffer may contain strings whose length after encoding is not yet known. So this number is only an approximation of the number of bytes in the buffer.
net.Socket
具有 socket.write()
始终有效的特性。 这是为了帮助用户快速启动和运行。 计算机无法始终跟上写入套接字的数据量。 网络连接可能太慢了。 Node.js 将在内部排队写入套接字的数据,并在可能时通过网络将其发送出去。
英net.Socket
has the property that socket.write()
always works. This is to
help users get up and running quickly. The computer cannot always keep up
with the amount of data that is written to a socket. The network connection
simply might be too slow. Node.js will internally queue up the data written to a
socket and send it out over the wire when it is possible.
这种内部缓冲的结果是内存可能会增长。
遇到较大或不断增长的 bufferSize
的用户应尝试使用 socket.pause()
和 socket.resume()
对他们程序中的数据流进行 "throttle"。
英The consequence of this internal buffering is that memory may grow.
Users who experience large or growing bufferSize
should attempt to
"throttle" the data flows in their program with
socket.pause()
and socket.resume()
.
socket.bytesRead
#
接收到的字节数。
英The amount of received bytes.
socket.bytesWritten
#
发送的字节数。
英The amount of bytes sent.
socket.connect()
#
在给定套接字上启动连接。
英Initiate a connection on a given socket.
可能的语法有:
英Possible signatures:
socket.connect(options[, connectListener])
socket.connect(path[, connectListener])
用于 IPC 连接。socket.connect(port[, host][, connectListener])
用于 TCP 连接。- 返回: <net.Socket> 套接字自身
这个函数是异步的。 建立连接后,将触发 'connect'
事件。 如果连接出现问题,而不是 'connect'
事件,将触发 'error'
事件并将错误传递给 'error'
监听器。
最后一个参数 connectListener
(如果提供)将添加为 'connect'
事件 once 的监听器。
英This function is asynchronous. When the connection is established, the
'connect'
event will be emitted. If there is a problem connecting,
instead of a 'connect'
event, an 'error'
event will be emitted with
the error passed to the 'error'
listener.
The last parameter connectListener
, if supplied, will be added as a listener
for the 'connect'
event once.
此函数只能用于在触发 'close'
后重新连接套接字,否则可能会导致未定义的行为。
英This function should only be used for reconnecting a socket after
'close'
has been emitted or otherwise it may lead to undefined
behavior.
socket.connect(options[, connectListener])
#
options
<Object>connectListener
<Function>socket.connect()
方法的常用参数。 将被添加为'connect'
事件的监听器一次。- 返回: <net.Socket> 套接字自身
在给定套接字上启动连接。 通常不需要此方法,应使用 net.createConnection()
创建并打开套接字。 仅在实现自定义套接字时使用它。
英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.
对于 TCP 连接,可用的 options
是:
英For TCP connections, available options
are:
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> 如果设置为正数,它会设置在空闲套接字上发送第一个 keepalive 探测之前的初始延迟。默认值:0
。autoSelectFamily
<boolean>: 如果设置为true
,它会启用一个家庭自动检测算法,该算法松散地实现了 RFC 8305 的第 5 节。 传递给 lookup 的all
选项设置为true
,套接字会依次尝试连接到所有获得的 IPv6 和 IPv4 地址,直到建立连接。 首先尝试返回的第一个 AAAA 地址,然后是第一个返回的 A 地址,然后是第二个返回的 AAAA 地址,依此类推。 在超时和尝试下一个地址之前,每次连接尝试都会获得autoSelectFamilyAttemptTimeout
选项指定的时间量。 如果family
选项不是0
或设置了localAddress
,则忽略。 如果至少有一个连接成功,则不会触发连接错误。 如果所有连接尝试都失败,则会触发包含所有失败尝试的单个AggregateError
。 默认值:net.getDefaultAutoSelectFamily()
autoSelectFamilyAttemptTimeout
<number>: 使用autoSelectFamily
选项时在尝试下一个地址之前等待连接尝试完成的时间量(以毫秒为单位)。 如果设置为小于10
的正整数,则将使用值10
。 默认值:net.getDefaultAutoSelectFamilyAttemptTimeout()
对于 IPC 连接,可用的 options
是:
英For IPC connections, available options
are:
path
<string> 必需的。 客户端应该连接的路径。 参见 识别 IPC 连接的路径。 如果提供,上面的 TCP 特定选项将被忽略。
对于这两种类型,可用的 options
包括:
英For both types, available options
include:
onread
<Object> 如果指定,传入的数据存储在单个buffer
中,并在数据到达套接字时传给提供的callback
。 这将导致流式传输功能不提供任何数据。 套接字将像往常一样触发'error'
、'end'
和'close'
等事件。pause()
和resume()
之类的方法也将按预期运行。buffer
<Buffer> | <Uint8Array> | <Function> 用于存储传入数据的可重用内存块或返回此类数据的函数。callback
<Function> 为每个传入数据块调用此函数。 传递给它的两个参数: 写入buffer
的字节数和对buffer
的引用。 从此函数返回false
以隐式pause()
套接字。 该函数将在全局上下文中执行。
以下是使用 onread
选项的客户端示例:
英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));
},
},
});
socket.connect(path[, connectListener])
#
path
<string> 客户端应该连接的路径。 参见 识别 IPC 连接的路径。connectListener
<Function>socket.connect()
方法的常用参数。 将被添加为'connect'
事件的监听器一次。- 返回: <net.Socket> 套接字自身
在给定套接字上启动 IPC 连接。
英Initiate an IPC connection on the given socket.
socket.connect(options[, connectListener])
的别名,{ path: path }
作为 options
调用。
英Alias to
socket.connect(options[, connectListener])
called with { path: path }
as options
.
socket.connect(port[, host][, connectListener])
#
port
<number> 客户端应该连接到的端口。host
<string> 客户端应该连接到的主机。connectListener
<Function>socket.connect()
方法的常用参数。 将被添加为'connect'
事件的监听器一次。- 返回: <net.Socket> 套接字自身
在给定的套接字上发起 TCP 连接。
英Initiate a TCP connection on the given socket.
socket.connect(options[, connectListener])
的别名,{port: port, host: host}
作为 options
调用。
英Alias to
socket.connect(options[, connectListener])
called with {port: port, host: host}
as options
.
socket.connecting
#
如果 true
,socket.connect(options[, connectListener])
被调用但尚未完成。 它将保持 true
直到套接字连接,然后将其设置为 false
并触发 'connect'
事件。 请注意,socket.connect(options[, connectListener])
回调是 'connect'
事件的监听器。
英If true
,
socket.connect(options[, connectListener])
was
called and has not yet finished. It will stay true
until the socket becomes
connected, then it is set to false
and the 'connect'
event is emitted. Note
that the
socket.connect(options[, connectListener])
callback is a listener for the 'connect'
event.
socket.destroy([error])
#
error
<Object>- 返回: <net.Socket>
确保此套接字上不再发生 I/O 活动。 销毁流并关闭连接。
英Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.
有关详细信息,请参阅 writable.destroy()
。
英See writable.destroy()
for further details.
socket.destroyed
#
- <boolean> 指示连接是否被破坏。 一旦连接被破坏,就无法使用它传输更多数据。
有关详细信息,请参阅 writable.destroyed
。
英See writable.destroyed
for further details.
socket.destroySoon()
#
写入所有数据后销毁套接字。 如果 'finish'
事件已经触发,则立即销毁套接字。 如果套接字仍然可写,它会隐式调用 socket.end()
。
英Destroys the socket after all data is written. If the 'finish'
event was
already emitted the socket is destroyed immediately. If the socket is still
writable it implicitly calls socket.end()
.
socket.end([data[, encoding]][, callback])
#
data
<string> | <Buffer> | <Uint8Array>encoding
<string> 仅当数据为string
时使用。 默认值:'utf8'
。callback
<Function> 套接字完成时的可选回调。- 返回: <net.Socket> 套接字自身
半关闭套接字。 即,它发送一个 FIN 数据包。 服务器可能仍会发送一些数据。
英Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.
有关详细信息,请参阅 writable.end()
。
英See writable.end()
for further details.
socket.localAddress
#
远程客户端正在连接的本地 IP 地址的字符串表示形式。 例如,在 '0.0.0.0'
上监听的服务器中,如果客户端连接到 '192.168.1.1'
,则 socket.localAddress
的值将为 '192.168.1.1'
。
英The string representation of the local IP address the remote client is
connecting on. For example, in a server listening on '0.0.0.0'
, if a client
connects on '192.168.1.1'
, the value of socket.localAddress
would be
'192.168.1.1'
.
socket.localPort
#
本地端口的数字表示。 例如,80
或 21
。
英The numeric representation of the local port. For example, 80
or 21
.
socket.localFamily
#
本地 IP 系列的字符串表示形式。 'IPv4'
或 'IPv6'
。
英The string representation of the local IP family. 'IPv4'
or 'IPv6'
.
socket.pause()
#
- 返回: <net.Socket> 套接字自身
暂停数据读取。 也就是说,不会触发 'data'
事件。
有助于限制上传。
英Pauses the reading of data. That is, 'data'
events will not be emitted.
Useful to throttle back an upload.
socket.pending
#
如果套接字尚未连接,则为 true
,因为 .connect()
尚未被调用,或者因为它仍在连接过程中(请参阅 socket.connecting
)。
英This is true
if the socket is not connected yet, either because .connect()
has not yet been called or because it is still in the process of connecting
(see socket.connecting
).
socket.ref()
#
- 返回: <net.Socket> 套接字自身
与 unref()
相反,如果它是唯一剩下的套接字(默认行为),则在之前 unref
化的套接字上调用 ref()
不会让程序退出。
如果套接字被 ref
ed 再次调用 ref
将无效。
英Opposite of unref()
, calling ref()
on a previously unref
ed socket will
not let the program exit if it's the only socket left (the default behavior).
If the socket is ref
ed calling ref
again will have no effect.
socket.remoteAddress
#
远程 IP 地址的字符串表示形式。 例如,'74.125.127.100'
或 '2001:4860:a005::68'
。 如果套接字被破坏(例如,如果客户端断开连接),则值可能是 undefined
。
英The string representation of the remote IP address. For example,
'74.125.127.100'
or '2001:4860:a005::68'
. Value may be undefined
if
the socket is destroyed (for example, if the client disconnected).
socket.remoteFamily
#
远程 IP 系列的字符串表示形式。 'IPv4'
或 'IPv6'
。 如果套接字被破坏(例如,如果客户端断开连接),则值可能是 undefined
。
英The string representation of the remote IP family. 'IPv4'
or 'IPv6'
. Value may be undefined
if
the socket is destroyed (for example, if the client disconnected).
socket.remotePort
#
远程端口的数字表示。 例如,80
或 21
。 如果套接字被破坏(例如,如果客户端断开连接),则值可能是 undefined
。
英The numeric representation of the remote port. For example, 80
or 21
. Value may be undefined
if
the socket is destroyed (for example, if the client disconnected).
socket.resetAndDestroy()
#
- 返回: <net.Socket>
通过发送 RST 数据包关闭 TCP 连接并销毁流。
如果这个 TCP 套接字处于连接状态,它会发送一个 RST 数据包,并在连接后销毁这个 TCP 套接字。
否则,它将调用 socket.destroy
并返回 ERR_SOCKET_CLOSED
错误。
如果这不是 TCP 套接字(例如管道),调用此方法将立即抛出 ERR_INVALID_HANDLE_TYPE
错误。
英Close the TCP connection by sending an RST packet and destroy the stream.
If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.
Otherwise, it will call socket.destroy
with an ERR_SOCKET_CLOSED
Error.
If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an ERR_INVALID_HANDLE_TYPE
Error.
socket.resume()
#
- 返回: <net.Socket> 套接字自身
调用 socket.pause()
后恢复阅读。
英Resumes reading after a call to socket.pause()
.
socket.setEncoding([encoding])
#
encoding
<string>- 返回: <net.Socket> 套接字自身
将套接字的编码设置为 可读流。 有关详细信息,请参阅 readable.setEncoding()
。
英Set the encoding for the socket as a Readable Stream. See
readable.setEncoding()
for more information.
socket.setKeepAlive([enable][, initialDelay])
#
enable
<boolean> 默认值:false
initialDelay
<number> 默认值:0
- 返回: <net.Socket> 套接字自身
启用/禁用保持活动功能,并可选择在空闲套接字上发送第一个保持活动探测之前设置初始延迟。
英Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket.
设置 initialDelay
(以毫秒为单位)以设置接收到的最后一个数据包和第一个 keepalive 探测之间的延迟。 为 initialDelay
设置 0
将使值保持默认(或先前)设置不变。
英Set initialDelay
(in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0
for
initialDelay
will leave the value unchanged from the default
(or previous) setting.
启用保持活动功能将设置以下套接字选项:
英Enabling the keep-alive functionality will set the following socket options:
SO_KEEPALIVE=1
TCP_KEEPIDLE=initialDelay
TCP_KEEPCNT=10
TCP_KEEPINTVL=1
socket.setNoDelay([noDelay])
#
noDelay
<boolean> 默认值:true
- 返回: <net.Socket> 套接字自身
启用/禁用 Nagle 算法的使用。
英Enable/disable the use of Nagle's algorithm.
创建 TCP 连接时,它将启用 Nagle 算法。
英When a TCP connection is created, it will have Nagle's algorithm enabled.
Nagle 的算法会在数据通过网络发送之前延迟数据。 它试图以延迟为代价来优化吞吐量。
英Nagle's algorithm delays data before it is sent via the network. It attempts to optimize throughput at the expense of latency.
为 noDelay
传递 true
或不传递参数将禁用套接字的 Nagle 算法。 为 noDelay
传递 false
将启用 Nagle 算法。
英Passing true
for noDelay
or not passing an argument will disable Nagle's
algorithm for the socket. Passing false
for noDelay
will enable Nagle's
algorithm.
socket.setTimeout(timeout[, callback])
#
timeout
<number>callback
<Function>- 返回: <net.Socket> 套接字自身
将套接字设置为在套接字上处于非活动状态 timeout
毫秒后超时。 默认情况下 net.Socket
没有超时。
英Sets the socket to timeout after timeout
milliseconds of inactivity on
the socket. By default net.Socket
do not have a timeout.
当触发空闲超时时,套接字将收到 'timeout'
事件,但连接不会被切断。 用户必须手动调用 socket.end()
或 socket.destroy()
来结束连接。
英When an idle timeout is triggered the socket will receive a 'timeout'
event but the connection will not be severed. The user must manually call
socket.end()
or socket.destroy()
to end the connection.
socket.setTimeout(3000);
socket.on('timeout', () => {
console.log('socket timeout');
socket.end();
});
如果 timeout
为 0,则禁用现有空闲超时。
英If timeout
is 0, then the existing idle timeout is disabled.
可选的 callback
参数将被添加为 'timeout'
事件的单次监听器。
英The optional callback
parameter will be added as a one-time listener for the
'timeout'
event.
socket.timeout
#
socket.setTimeout()
设置的套接字超时(以毫秒为单位)。
如果没有设置超时则为 undefined
。
英The socket timeout in milliseconds as set by socket.setTimeout()
.
It is undefined
if a timeout has not been set.
socket.unref()
#
- 返回: <net.Socket> 套接字自身
如果这是事件系统中唯一活动的套接字,则在套接字上调用 unref()
将允许程序退出。 如果套接字已经 unref
ed 再次调用 unref()
将无效。
英Calling unref()
on a socket will allow the program to exit if this is the only
active socket in the event system. If the socket is already unref
ed calling
unref()
again will have no effect.
socket.write(data[, encoding][, callback])
#
data
<string> | <Buffer> | <Uint8Array>encoding
<string> 仅当数据为string
时使用。 默认值:utf8
。callback
<Function>- 返回: <boolean>
在套接字上发送数据。 第二个参数指定字符串情况下的编码。 它默认为 UTF8 编码。
英Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding.
如果整个数据被成功刷新到内核缓冲区,则返回 true
。 如果所有或部分数据在用户内存中排队,则返回 false
。
当缓冲区再次空闲时,将触发 'drain'
。
英Returns true
if the entire data was flushed successfully to the kernel
buffer. Returns false
if all or part of the data was queued in user memory.
'drain'
will be emitted when the buffer is again free.
可选的 callback
参数将在数据最终写出时执行,这可能不会立即执行。
英The optional callback
parameter will be executed when the data is finally
written out, which may not be immediately.
有关详细信息,请参阅 Writable
流 write()
方法。
英See Writable
stream write()
method for more
information.
socket.readyState
#
此属性将连接状态表示为字符串。
英This property represents the state of the connection as a string.
- 如果流正在连接
socket.readyState
是opening
。 - 如果流可读可写,则为
open
。 - 如果流可读不可写,则为
readOnly
。 - 如果流不可读写,则为
writeOnly
。
net.connect()
#
英Aliases to
net.createConnection()
.
可能的语法有:
英Possible signatures:
net.connect(options[, connectListener])
net.connect(path[, connectListener])
用于 IPC 连接。net.connect(port[, host][, connectListener])
用于 TCP 连接。
net.connect(options[, connectListener])
#
options
<Object>connectListener
<Function>- 返回: <net.Socket>
net.createConnection(options[, connectListener])
的别名。
英Alias to
net.createConnection(options[, connectListener])
.
net.connect(path[, connectListener])
#
path
<string>connectListener
<Function>- 返回: <net.Socket>
net.createConnection(path[, connectListener])
的别名。
英Alias to
net.createConnection(path[, connectListener])
.
net.connect(port[, host][, connectListener])
#
port
<number>host
<string>connectListener
<Function>- 返回: <net.Socket>
net.createConnection(port[, host][, connectListener])
的别名。
英Alias to
net.createConnection(port[, host][, connectListener])
.
net.createConnection()
#
创建新的 net.Socket
的工厂函数立即启动与 socket.connect()
的连接,然后返回启动连接的 net.Socket
。
英A factory function, which creates a new net.Socket
,
immediately initiates connection with socket.connect()
,
then returns the net.Socket
that starts the connection.
建立连接后,将在返回的套接字上触发 'connect'
事件。 最后一个参数 connectListener
(如果提供)将添加为 'connect'
事件 once 的监听器。
英When the connection is established, a 'connect'
event will be emitted
on the returned socket. The last parameter connectListener
, if supplied,
will be added as a listener for the 'connect'
event once.
可能的语法有:
英Possible signatures:
net.createConnection(options[, connectListener])
net.createConnection(path[, connectListener])
用于 IPC 连接。net.createConnection(port[, host][, connectListener])
用于 TCP 连接。
net.connect()
函数是此函数的别名。
英The net.connect()
function is an alias to this function.
net.createConnection(options[, connectListener])
#
options
<Object> 必需的。 将传递给new net.Socket([options])
调用和socket.connect(options[, connectListener])
方法。connectListener
<Function>net.createConnection()
函数的通用参数。 如果提供,将被添加为返回套接字上的'connect'
事件的监听器一次。- 返回: <net.Socket> 用于启动连接的新创建的套接字。
有关可用选项,请参阅 new net.Socket([options])
和 socket.connect(options[, connectListener])
。
英For available options, see
new net.Socket([options])
and socket.connect(options[, connectListener])
.
其他选项:
英Additional options:
timeout
<number> 如果设置,则将用于在创建套接字之后但在开始连接之前调用socket.setTimeout(timeout)
。
以下是 net.createServer()
部分中描述的回显服务器的客户端示例:
英Following is an example of a client of the echo server described
in the net.createServer()
section:
const net = require('node:net');
const client = net.createConnection({ port: 8124 }, () => {
// 'connect' listener.
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
要连接到套接字 /tmp/echo.sock
:
英To connect on the socket /tmp/echo.sock
:
const client = net.createConnection({ path: '/tmp/echo.sock' });
net.createConnection(path[, connectListener])
#
path
<string> 套接字应连接到的路径。 将传递给socket.connect(path[, connectListener])
。 参见 识别 IPC 连接的路径。connectListener
<Function>net.createConnection()
函数的公共参数,发起套接字上的'connect'
事件的 "once" 监听器。 将传递给socket.connect(path[, connectListener])
。- 返回: <net.Socket> 用于启动连接的新创建的套接字。
启动 IPC 连接。
英Initiates an IPC connection.
此函数创建新的 net.Socket
,所有选项都设置为默认值,立即启动与 socket.connect(path[, connectListener])
的连接,然后返回启动连接的 net.Socket
。
英This function creates a new net.Socket
with all options set to default,
immediately initiates connection with
socket.connect(path[, connectListener])
,
then returns the net.Socket
that starts the connection.
net.createConnection(port[, host][, connectListener])
#
port
<number> 套接字应连接到的端口。 将传递给socket.connect(port[, host][, connectListener])
。host
<string> 套接字应连接到的主机。 将传递给socket.connect(port[, host][, connectListener])
。 默认值:'localhost'
。connectListener
<Function>net.createConnection()
函数的公共参数,发起套接字上的'connect'
事件的 "once" 监听器。 将传递给socket.connect(port[, host][, connectListener])
。- 返回: <net.Socket> 用于启动连接的新创建的套接字。
发起 TCP 连接。
英Initiates a TCP connection.
此函数创建新的 net.Socket
,所有选项都设置为默认值,立即启动与 socket.connect(port[, host][, connectListener])
的连接,然后返回启动连接的 net.Socket
。
英This function creates a new net.Socket
with all options set to default,
immediately initiates connection with
socket.connect(port[, host][, connectListener])
,
then returns the net.Socket
that starts the connection.
net.createServer([options][, connectionListener])
#
-
options
<Object>allowHalfOpen
<boolean> 如果设置为false
,则当可读端结束时,套接字将自动结束可写端。 默认值:false
。highWaterMark
<number> 可选择覆盖所有net.Socket
'readableHighWaterMark
和writableHighWaterMark
。 默认值: 参见stream.getDefaultHighWaterMark()
。pauseOnConnect
<boolean> 指示是否应在传入连接上暂停套接字。 默认值:false
。noDelay
<boolean> 如果设置为true
,则它会在收到新的传入连接后立即禁用 Nagle 算法。 默认值:false
。keepAlive
<boolean> 如果设置为true
,则它会在接收到新的传入连接后立即在套接字上启用保持活动功能,类似于在socket.setKeepAlive([enable][, initialDelay])
中所做的。 默认值:false
。keepAliveInitialDelay
<number> 如果设置为正数,它会设置在空闲套接字上发送第一个 keepalive 探测之前的初始延迟。默认值:0
。
-
connectionListener
<Function> 自动设置为'connection'
事件的监听器。 -
返回: <net.Server>
创建新的 TCP 或 IPC 服务器。
英Creates a new TCP or IPC server.
如果 allowHalfOpen
设置为 true
,当套接字的另一端触发传输结束信号时,服务器只有在显式调用 socket.end()
时才发回传输结束。 例如,在 TCP 上下文中,当接收到 FIN 打包时,只有在显式调用 socket.end()
时才会发回 FIN 打包。 在此之前,连接处于半关闭状态(不可读但仍可写)。 有关详细信息,请参阅 'end'
事件和 RFC 1122(第 4.2.2.13 节)。
英If allowHalfOpen
is set to true
, when the other end of the socket
signals the end of transmission, the server will only send back the end of
transmission when socket.end()
is explicitly called. For example, in the
context of TCP, when a FIN packed is received, a FIN packed is sent
back only when socket.end()
is explicitly called. Until then the
connection is half-closed (non-readable but still writable). See 'end'
event and RFC 1122 (section 4.2.2.13) for more information.
如果 pauseOnConnect
设置为 true
,则与每个传入连接关联的套接字将被暂停,并且不会从其句柄读取数据。
这允许在进程之间传递连接,而原始进程不会读取任何数据。 要开始从暂停的套接字读取数据,则调用 socket.resume()
。
英If pauseOnConnect
is set to true
, then the socket associated with each
incoming connection will be paused, and no data will be read from its handle.
This allows connections to be passed between processes without any data being
read by the original process. To begin reading data from a paused socket, call
socket.resume()
.
服务器可以是 TCP 服务器或 IPC 服务器,具体取决于它 listen()
的用途。
英The server can be a TCP server or an IPC server, depending on what it
listen()
to.
这是一个 TCP 回显服务器的示例,它监听端口 8124 上的连接:
英Here is an example of a TCP echo server which listens for connections on port 8124:
const net = require('node:net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
使用 telnet
对此进行测试:
英Test this by using telnet
:
telnet localhost 8124
要监听套接字 /tmp/echo.sock
:
英To listen on the socket /tmp/echo.sock
:
server.listen('/tmp/echo.sock', () => {
console.log('server bound');
});
使用 nc
连接到 Unix 域套接字服务器:
英Use nc
to connect to a Unix domain socket server:
nc -U /tmp/echo.sock
net.getDefaultAutoSelectFamily()
#
获取 socket.connect(options)
的 autoSelectFamily
选项的当前默认值。
初始默认值为 true
,除非提供了命令行选项 --no-network-family-autoselection
。
英Gets the current default value of the autoSelectFamily
option of socket.connect(options)
.
The initial default value is true
, unless the command line option
--no-network-family-autoselection
is provided.
- 返回: <boolean>
autoSelectFamily
选项的当前默认值。
net.setDefaultAutoSelectFamily(value)
#
设置 socket.connect(options)
的 autoSelectFamily
选项的默认值。
英Sets the default value of the autoSelectFamily
option of socket.connect(options)
.
value
<boolean> 新的默认值。 初始默认值为false
。
net.getDefaultAutoSelectFamilyAttemptTimeout()
#
获取 socket.connect(options)
的 autoSelectFamilyAttemptTimeout
选项的当前默认值。
初始默认值为 250
。
英Gets the current default value of the autoSelectFamilyAttemptTimeout
option of socket.connect(options)
.
The initial default value is 250
.
- 返回: <number>
autoSelectFamilyAttemptTimeout
选项的当前默认值。
net.setDefaultAutoSelectFamilyAttemptTimeout(value)
#
设置 socket.connect(options)
的 autoSelectFamilyAttemptTimeout
选项的默认值。
英Sets the default value of the autoSelectFamilyAttemptTimeout
option of socket.connect(options)
.
value
<number> 新的默认值,必须是正数。 如果数字小于10
,则使用值10
。 初始默认值为250
。
net.isIP(input)
#
如果 input
是 IPv6 地址,则返回 6
。 如果 input
是 点十进制表示法 中没有前导零的 IPv4 地址,则返回 4
。 否则,返回 0
。
英Returns 6
if input
is an IPv6 address. Returns 4
if input
is an IPv4
address in dot-decimal notation with no leading zeroes. Otherwise, returns
0
.
net.isIP('::1'); // returns 6
net.isIP('127.0.0.1'); // returns 4
net.isIP('127.000.000.001'); // returns 0
net.isIP('127.0.0.1/24'); // returns 0
net.isIP('fhqwhgads'); // returns 0
net.isIPv4(input)
#
如果 input
是 点十进制表示法 中没有前导零的 IPv4 地址,则返回 true
。 否则,返回 false
。
英Returns true
if input
is an IPv4 address in dot-decimal notation with no
leading zeroes. Otherwise, returns false
.
net.isIPv4('127.0.0.1'); // returns true
net.isIPv4('127.000.000.001'); // returns false
net.isIPv4('127.0.0.1/24'); // returns false
net.isIPv4('fhqwhgads'); // returns false
net.isIPv6(input)
#
如果 input
是 IPv6 地址,则返回 true
。 否则,返回 false
。
英Returns true
if input
is an IPv6 address. Otherwise, returns false
.
net.isIPv6('::1'); // returns true
net.isIPv6('fhqwhgads'); // returns false