- 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.20.6 文档
- Node.js v20.20.6
-
目录
- 网络
- IPC 支持
- 类:
net.BlockList - 类:
net.SocketAddress - 类:
net.Server - 类:
net.Socketnew net.Socket([options])- 事件:
'close' - 事件:
'connect' - 事件:
'connectionAttempt' - 事件:
'connectionAttemptFailed' - 事件:
'connectionAttemptTimeout' - 事件:
'data' - 事件:
'drain' - 事件:
'end' - 事件:
'错误' - 事件:
'lookup' - 事件:
'ready' - 事件:
'timeout' socket.address()socket.autoSelectFamilyAttemptedAddressessocket.bufferSizesocket.bytesReadsocket.bytesWrittensocket.connect()socket.connectingsocket.destroy([error])socket.destroyedsocket.destroySoon()socket.end([data[, encoding]][, callback])socket.localAddresssocket.localPortsocket.localFamilysocket.pause()socket.pendingsocket.ref()socket.remoteAddresssocket.remoteFamilysocket.remotePortsocket.resetAndDestroy()socket.resume()socket.setEncoding([encoding])socket.setKeepAlive([enable][, initialDelay])socket.setNoDelay([noDelay])socket.setTimeout(timeout[, callback])socket.timeoutsocket.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 压缩
- 其他版本
网络#>
【Net】
源代码: 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:】
import net from 'node:net';const net = require('node:net');
IPC 支持#>
【IPC support】
node:net 模块在 Windows 上支持通过命名管道进行 IPC,在其他操作系统上支持通过 Unix 域套接字进行 IPC。
【The node:net module supports IPC with named pipes on Windows, and Unix domain
sockets on other operating systems.】
识别 IPC 连接的路径#>
【Identifying paths for IPC connections】
net.connect()、net.createConnection()、server.listen() 和 socket.connect() 采用 path 参数来识别 IPC 端点。
在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 域套接字会在文件系统中可见,且
会持续存在直到解除绑定。在 Linux 上,你可以通过添加 Unix 抽象套接字来使用
“\0” 映射到路径起始,例如 “\0abstract”。通往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. On Linux, You can use Unix abstract socket by adding
\0 to the beginning of the path, such as \0abstract. The path to the Unix
abstract socket is not visible in the file system and it will disappear automatically
when all open references to the socket are closed.】
在 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#>
【Class: 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#>
【Class: net.SocketAddress】
new net.SocketAddress([options])#>
options<Object>
socketaddress.address#>
- 输入 <string>
socketaddress.family#>
- 类型 <string> 可以是
'ipv4'或'ipv6'。
socketaddress.flowlabel#>
- 输入 <number>
socketaddress.port#>
- 输入 <number>
类:net.Server#>
【Class: 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:
事件:'close'#>
【Event: 'close'】
当服务器关闭时触发。如果存在连接,则在所有连接结束之前不会触发此事件。
【Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.】
事件:'connection'#>
【Event: 'connection'】
- <net.Socket> 连接对象
当建立新连接时触发。socket 是 net.Socket 的一个实例。
【Emitted when a new connection is made. socket is an instance of
net.Socket.】
事件:'错误'#>
【Event: 'error'】
当发生错误时触发。与 net.Socket 不同,'close' 事件不会在此事件之后直接触发,除非手动调用 server.close()。请参见关于 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'#>
【Event: 'listening'】
在调用 server.listen() 后服务器绑定时触发。
【Emitted when the server has been bound after calling server.listen().】
事件:'drop'#>
【Event: '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()#>
返回绑定的 address、地址 family 名称和服务器的 port,如果监听的是 IP 套接字,则由操作系统报告(在获取操作系统分配的地址时,用于查找分配的端口):{ 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.close([callback])#>
callback<Function> 当服务器关闭时调用。- 返回值: <net.Server>
阻止服务器接受新的连接,并保持现有连接。此函数是异步的,当所有连接结束并且服务器触发 'close' 事件时,服务器最终关闭。可选的 callback 会在 'close' 事件发生后被调用。与该事件不同,如果服务器在关闭时未开启,它将以 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(handle)`] server.listen(options[, callback])- [
server.listen(path[, backlog][, callback])][server.listen(path)`] 适用于 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.listen() 时发生错误或已调用 server.close() 时才能再次调用。否则,将抛出 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> 必填。支持以下属性:backlog<number>server.listen()功能的常用参数。exclusive<boolean> 默认值:falsehost<string>ipv6Only<boolean> 对于 TCP 服务器,将ipv6Only设置为true将禁用双协议栈支持,即绑定到主机::不会导致0.0.0.0被绑定。默认值:false。path<string> 如果指定了port将被忽略。详见 识别 IPC 连接的路径。port<number>readableAll<boolean> 对于 IPC 服务器,使管道对所有用户可读。默认值:false。signal<AbortSignal> 一个用于关闭监听服务器的 AbortSignal。writableAll<boolean> 对于 IPC 服务器,使管道对所有用户可写。默认值:false。*callback<Function> 函数。* 返回值:<net.Server>
如果指定了 port,它的行为与 server.listen([port[, host[, backlog]]][, callback]) 相同。否则,如果指定了 path,它的行为与 server.listen(path) 相同。如果两者都未指定,将会抛出错误。
【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 且底层句柄被共享时,可能会有多个工作进程使用不同的积压队列查询同一个句柄。在这种情况下,传递给主进程的第一个 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 过的服务器上调用 ref(),如果这是最后一个服务器,程序将 不会 退出(这是默认行为)。如果服务器已经是 ref 状态,再次调用 ref() 不会有任何效果。
【Opposite of unref(), calling ref() on a previously unrefed server will
not let the program exit if it's the only server left (the default behavior).
If the server is refed calling ref() again will have no effect.】
server.unref()#>
- 返回: <net.Server>
在服务器上调用 unref() 会允许程序退出,如果这是事件系统中唯一的活动服务器。如果服务器已经被 unref,再次调用 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 unrefed calling
unref() again will have no effect.】
类:net.Socket#>
【Class: 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> 可用选项有:allowHalfOpen<boolean> 如果设置为false,当可读端结束时,套接字将自动结束可写端。详情请参见net.createServer()和'end'事件。 默认值:false。fd<number> 如果指定,将使用给定的文件描述符封装一个现有的套接字,否则将创建一个新的套接字。onread<Object> 如果指定,传入的数据将存储在单个buffer中,并在套接字接收到数据时传递给提供的callback。这将导致流功能不提供任何数据。套接字仍将像往常一样触发'error'、'end'和'close'等事件。像pause()和resume()这样的方法也会按预期工作。buffer<Buffer> | <Uint8Array> | <Function> 可用于存储传入数据的可重复使用的内存块,或者返回此类内存块的函数。callback<Function> 该函数会在每个接收到的数据块时被调用。它接收两个参数:写入buffer的字节数以及buffer的引用。从该函数返回false会隐式地pause()套接字。此函数将在全局上下文中执行。
readable<boolean> 当传入fd时允许对套接字进行读取,否则忽略。默认值:false。signal<AbortSignal> 一种中止信号,可用于销毁套接字。writable<boolean> 当传入fd时允许对套接字进行写操作,否则忽略。默认值:false。
- 返回值: <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'#>
【Event: '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'#>
【Event: 'connect'】
当套接字连接成功建立时触发。请参见 net.createConnection()。
【Emitted when a socket connection is successfully established.
See net.createConnection().】
事件:'connectionAttempt'#>
【Event: 'connectionAttempt'】
当开始新的连接尝试时触发。如果在 socket.connect(options) 中启用了网络类型自动选择算法,可能会多次触发此事件。
【Emitted when a new connection attempt is started. This may be emitted multiple times
if the family autoselection algorithm is enabled in socket.connect(options).】
事件:'connectionAttemptFailed'#>
【Event: 'connectionAttemptFailed'】
ip<string> 套接字尝试连接的 IP 地址。port<number> 套接字尝试连接的端口。family<number> IP 的类型。可以是 IPv6 的6或 IPv4 的4。error<Error> 与失败相关的错误。
当连接尝试失败时发出。如果在 socket.connect(options) 中启用了地址族自动选择算法,可能会多次发出此事件。
【Emitted when a connection attempt failed. This may be emitted multiple times
if the family autoselection algorithm is enabled in socket.connect(options).】
事件:'connectionAttemptTimeout'#>
【Event: 'connectionAttemptTimeout'】
当连接尝试超时时发出。仅当 socket.connect(options) 中启用了地址族自动选择算法时才会发出(并且可能会发出多次)。
【Emitted when a connection attempt timed out. This is only emitted (and may be
emitted multiple times) if the family autoselection algorithm is enabled
in socket.connect(options).】
事件:'data'#>
【Event: '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'#>
【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'#>
【Event: '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() 来关闭连接(即发送一个 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).】
事件:'错误'#>
【Event: 'error'】
当发生错误时触发。在此事件之后将直接调用 'close' 事件。
【Emitted when an error occurs. The 'close' event will be called directly
following this event.】
事件:'lookup'#>
【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'#>
【Event: 'ready'】
当套接字准备好使用时触发。
【Emitted when a socket is ready to be used.】
在 'connect' 之后立即触发。
【Triggered immediately after 'connect'.】
事件:'timeout'#>
【Event: '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 会在内部将写入套接字的数据排队,并在可能的时候通过网络发送出去。
这种内部缓冲的结果是内存可能会增长。遇到 bufferSize 很大或增长的用户应尝试使用 socket.pause() 和 socket.resume() 来“节流”程序中的数据流。
【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(端口[, 主机]][, connectListener])用于 TCP 连接。- 返回值: <net.Socket> 套接字本身。
此函数是异步的。当连接建立时,将触发 'connect' 事件。如果连接时出现问题,不会触发 'connect' 事件,而会触发 'error' 事件,并将错误传递给 'error' 监听器。最后一个参数 connectListener,如果提供,将作为 'connect' 事件的监听器被添加,只触发一次。
【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:】
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()。family<number>:IP 堆栈的版本。必须是4、6或0。值0表示允许同时使用 IPv4 和 IPv6 地址。默认值:0。hints<number> 可选dns.lookup()提示。host<string> 套接字应连接的主机。默认值:'localhost'。keepAlive<boolean> 如果设置为true,在连接建立后会立即在套接字上启用保持连接功能,这与在socket.setKeepAlive()中的操作类似。默认值:false。keepAliveInitialDelay<number> 如果设置为正数,它会在空闲套接字上发送第一个保活探测之前设置初始延迟。 默认值:0。localAddress<string> 套接字应从其连接的本地地址。localPort<number> 套接字应从其连接的本地端口。lookup<Function> 自定义查找函数。默认值:dns.lookup()。noDelay<boolean> 如果设置为true,则在套接字建立后立即禁用 Nagle 算法。默认值:false。port<number> 必填。套接字应连接的端口。
对于 IPC 连接,可用的 选项 有:
【For IPC connections, available options are:】
path<string> 必需。客户端应连接的路径。 参见 识别 IPC 连接的路径。如果提供,上述 TCP 特定选项将被忽略。
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> 仅在 data 为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 状态,再次调用 ref 不会有任何效果。
【Opposite of unref(), calling ref() on a previously unrefed socket will
not let the program exit if it's the only socket left (the default behavior).
If the socket is refed 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> 默认值:falseinitialDelay<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(以毫秒为单位)以设置从接收到最后一个数据包到第一次保持活动探测之间的延迟时间。将 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=1TCP_KEEPIDLE=initialDelayTCP_KEEPCNT=10TCP_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.】
将 true 传递给 noDelay 或不传递参数将会禁用该套接字的 Nagle 算法。将 false 传递给 noDelay 则会启用 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,再次调用 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 unrefed calling
unref() again will have no effect.】
socket.write(data[, encoding][, callback])#>
data<string> | <Buffer> | <Uint8Array>encoding<string> 仅在 data 为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)用于 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(端口[, 主机][, 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' 事件的监听器 一次性 添加。
【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(端口[, 主机][, 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:】
import net from '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');
});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' });
以下是一个客户端使用 port 和 onread 选项的示例。在这种情况下,onread 选项将仅用于调用 new net.Socket([options]),而 port 选项将用于调用 socket.connect(options[, connectListener])。
【Following is an example of a client using the port and onread
option. In this case, the onread option will be only used to call
new net.Socket([options]) and the port option will be used to
call socket.connect(options[, connectListener]).】
import net from 'node:net';
import { Buffer } from 'node:buffer';
net.createConnection({
port: 8124,
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));
},
},
});const net = require('node:net');
net.createConnection({
port: 8124,
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));
},
},
});
net.createConnection(path[, connectListener])#>
path<string> 套接字应连接的路径。将传递给socket.connect(path[, connectListener])。见 识别 IPC 连接的路径。connectListener<Function>net.createConnection()函数的常用参数,发起套接字'connect'事件的一次性监听器。将传递给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(端口[, 主机]][, connectListener])。host<string> 套接字应连接的主机。将被传递给socket.connect(端口[, 主机]][, connectListener])。 默认值:'localhost'。connectListener<Function>net.createConnection()函数的通用参数,发起套接字的'connect'事件的“一次性”监听器。将被传递给socket.connect(端口[, 主机]][, connectListener])。- 返回值: <net.Socket> 用于启动连接的新创建套接字。
发起 TCP 连接。
【Initiates a TCP connection.】
此函数创建一个新的 net.Socket,所有选项都设置为默认值,立即与 [socket.connect(端口[, 主机]][, connectListener] 建立连接 socket.connect(port),然后返回启动连接的 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()。keepAlive<boolean> 如果设置为true,将在接收到新的传入连接后立即在套接字上启用保持活动功能,类似于在socket.setKeepAlive()中所做的操作。 默认值:false。keepAliveInitialDelay<number> 如果设置为正数,它会在空闲套接字上发送第一个保活探测之前设置初始延迟。 默认值:0。- “noDelay” <boolean> 如果设置为“true”,则禁用Nagle的 算法在接收到新入连接后立即执行。 默认: 'false'。
pauseOnConnect<boolean> 指示在有传入连接时套接字是否应暂停。默认值:false。
-
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:】
import net from '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');
});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> 新的默认值。
初始默认值为true,除非提供命令行选项--no-network-family-autoselection。
net.getDefaultAutoSelectFamilyAttemptTimeout()#>
获取 socket.connect(options) 的 autoSelectFamilyAttemptTimeout 选项的当前默认值。初始默认值为 250,或通过命令行选项 --network-family-autoselection-attempt-timeout 指定的值。
【Gets the current default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).
The initial default value is 250 or the value specified via the command line
option --network-family-autoselection-attempt-timeout.】
- 返回:<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,或者通过命令行选项--network-family-autoselection-attempt-timeout指定的值。
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