Node.js v22.11.0 文档


网络#

¥Net

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: 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 域套接字。

¥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 端点。

¥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 域套接字将在文件系统中可见,并且会一直存在直到取消链接。在 Linux 上,你可以通过在路径开头添加 \0 来使用 Unix 抽象套接字,例如 \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])#

添加规则以阻止给定的 IP 地址。

¥Adds a rule to block the given IP address.

blockList.addRange(start, end[, type])#

添加规则以阻止从 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 地址。

    ¥net <string> | <net.SocketAddress> The network IPv4 or IPv6 address.

  • prefix <number> CIDR 前缀位数。对于 IPv4,这必须是 032 之间的值。对于 IPv6,它必须在 0128 之间。

    ¥prefix <number> The number of CIDR prefix bits. For IPv4, this must be a value between 0 and 32. For IPv6, this must be between 0 and 128.

  • type <string> 'ipv4''ipv6'。默认值:'ipv4'

    ¥type <string> Either 'ipv4' or 'ipv6'. Default: 'ipv4'.

添加规则以阻止指定为子网掩码的 IP 地址范围。

¥Adds a rule to block a range of IP addresses specified as a subnet mask.

blockList.check(address[, type])#

如果给定的 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#

添加到阻止列表的规则列表。

¥The list of rules added to the blocklist.

类:net.SocketAddress#

¥Class: net.SocketAddress

new net.SocketAddress([options])#

  • options <Object>

    • address <string> 作为 IPv4 或 IPv6 字符串的网络地址。默认值:'127.0.0.1' 如果 family'ipv4''::' 如果 family'ipv6'

      ¥address <string> The network address as either an IPv4 or IPv6 string. Default: '127.0.0.1' if family is 'ipv4'; '::' if family is 'ipv6'.

    • family <string> 'ipv4''ipv6' 之一。默认值:'ipv4'

      ¥family <string> One of either 'ipv4' or 'ipv6'. Default: 'ipv4'.

    • flowlabel <number> 仅当 family'ipv6' 时才使用的 IPv6 流标签。

      ¥flowlabel <number> An IPv6 flow-label used only if family is 'ipv6'.

    • port <number> IP 端口。

      ¥port <number> An IP port.

socketaddress.address#

socketaddress.family#

socketaddress.flowlabel#

socketaddress.port#

类:net.Server#

¥Class: net.Server

此类用于创建 TCP 或 IPC 服务器。

¥This class is used to create a TCP or IPC server.

new net.Server([options][, connectionListener])#

net.Server 是具有以下事件的 EventEmitter

¥net.Server is an EventEmitter with the following events:

事件:'close'#

¥Event: 'close'

服务器关闭时触发。如果连接存在,则在所有连接结束之前不会触发此事件。

¥Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.

事件:'connection'#

¥Event: 'connection'

建立新连接时触发。socketnet.Socket 的实例。

¥Emitted when a new connection is made. socket is an instance of net.Socket.

事件:'error'#

¥Event: 'error'

发生错误时触发。与 net.Socket 不同的是,除非手动调用 server.close(),否则不会在该事件之后直接触发 '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> 传给事件监听器的参数。

    ¥data <Object> The argument passed to event listener.

    • localAddress <string> 本地地址。

      ¥localAddress <string> Local address.

    • localPort <number> 本地端口。

      ¥localPort <number> Local port.

    • localFamily <string> 本地族。

      ¥localFamily <string> Local family.

    • remoteAddress <string> 远程地址。

      ¥remoteAddress <string> Remote address.

    • remotePort <number> 远程端口。

      ¥remotePort <number> Remote port.

    • remoteFamily <string> 远程 IP 系列。'IPv4''IPv6'

      ¥remoteFamily <string> Remote IP family. 'IPv4' or 'IPv6'.

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])#

停止服务器接受新连接并保持现有连接。该函数是异步的,当所有连接都结束并且服务器触发 '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]()#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

调用 server.close() 并返回一个在服务器关闭时履行的 promise。

¥Calls server.close() and returns a promise that fulfills when the server has closed.

server.getConnections(callback)#

异步获取服务器上的并发连接数。当套接字被发送到复刻时工作。

¥Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.

回调应该采用两个参数 errcount

¥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:

这个函数是异步的。当服务器开始监听时,将触发 '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_backlogsomaxconn。此参数的默认值为 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 上的连接,该 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> 必需的。支持以下属性:

    ¥options <Object> Required. Supports the following properties:

    • backlog <number> server.listen() 函数的通用参数。

      ¥backlog <number> Common parameter of server.listen() functions.

    • exclusive <boolean> 默认值:false

      ¥exclusive <boolean> Default: false

    • host <string>

    • ipv6Only <boolean> 对于 TCP 服务器,将 ipv6Only 设置为 true 将禁用双栈支持,即绑定到主机 :: 不会绑定 0.0.0.0。默认值:false

      ¥ipv6Only <boolean> For TCP servers, setting ipv6Only to true will disable dual-stack support, i.e., binding to host :: won't make 0.0.0.0 be bound. Default: false.

    • path <string> 如果指定了 port,则将被忽略。参见 识别 IPC 连接的路径

      ¥path <string> Will be ignored if port is specified. See Identifying paths for IPC connections.

    • port <number>

    • readableAll <boolean> 对于 IPC 服务器,使管道对所有用户都可读。默认值:false

      ¥readableAll <boolean> For IPC servers makes the pipe readable for all users. Default: false.

    • signal <AbortSignal> 可用于关闭监听服务器的中止信号。

      ¥signal <AbortSignal> An AbortSignal that may be used to close a listening server.

    • writableAll <boolean> 对于 IPC 服务器,使管道对所有用户都可写。默认值:false

      ¥writableAll <boolean> For IPC servers makes the pipe writable for all users. Default: false.

  • callback <Function> 函数。

    ¥callback <Function> functions.

  • 返回:<net.Server>

    ¥Returns: <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.

如果 exclusivefalse(默认值),那么集群工作者将使用相同的底层句柄,允许共享连接处理职责。当 exclusivetrue 时,句柄未共享,尝试端口共享会导致错误。下面显示了一个监听独占端口的示例。

¥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,
}); 

exclusivetrue 且底层 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 服务器可能会导致非特权用户无法访问服务器路径。使用 readableAllwritableAll 将使所有用户都可以访问服务器。

¥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])#

启动 IPC 服务器监听给定 path 上的连接。

¥Start an IPC server listening for connections on the given path.

server.listen([port[, host[, backlog]]][, callback])#

启动 TCP 服务器监听给定 porthost 上的连接。

¥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> 指示服务器是否正在监听连接。

    ¥<boolean> Indicates whether or not the server is listening for connections.

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()#

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()#

如果这是事件系统中唯一活动的服务器,则在服务器上调用 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

此类是 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> 可用的选项有:

    ¥options <Object> Available options are:

    • allowHalfOpen <boolean> 如果设置为 false,则当可读端结束时,套接字将自动结束可写端。有关详细信息,请参阅 net.createServer()'end' 事件。默认值:false

      ¥allowHalfOpen <boolean> If set to false, then the socket will automatically end the writable side when the readable side ends. See net.createServer() and the 'end' event for details. Default: false.

    • fd <number> 如果指定,则使用给定的文件描述符封装现有的套接字,否则将创建新的套接字。

      ¥fd <number> If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.

    • onread <Object> 如果指定,传入的数据存储在单个 buffer 中,并在数据到达套接字时传给提供的 callback。这将导致流式传输功能不提供任何数据。套接字将像往常一样触发 'error''end''close' 等事件。pause()resume() 之类的方法也将按预期运行。

      ¥onread <Object> If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. This will cause the streaming functionality to not provide any data. The socket will emit events like 'error', 'end', and 'close' as usual. Methods like pause() and resume() will also behave as expected.

      • buffer <Buffer> | <Uint8Array> | <Function> 用于存储传入数据的可重用内存块或返回此类数据的函数。

        ¥buffer <Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to use for storing incoming data or a function that returns such.

      • callback <Function> 为每个传入数据块调用此函数。传递给它的两个参数:写入 buffer 的字节数和对 buffer 的引用。从此函数返回 false 以隐式 pause() 套接字。该函数将在全局上下文中执行。

        ¥callback <Function> This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. Return false from this function to implicitly pause() the socket. This function will be executed in the global context.

    • readable <boolean> 当传入 fd 时,则允许在套接字上读取,否则将被忽略。默认值:false

      ¥readable <boolean> Allow reads on the socket when an fd is passed, otherwise ignored. Default: false.

    • signal <AbortSignal> 可用于销毁套接字的中止信号。

      ¥signal <AbortSignal> An Abort signal that may be used to destroy the socket.

    • writable <boolean> 当传入 fd 时,则允许在套接字上写入,否则将被忽略。默认值:false

      ¥writable <boolean> Allow writes on the socket when an fd is passed, otherwise ignored. Default: false.

  • 返回:<net.Socket>

    ¥Returns: <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 <boolean> true if the socket had a transmission error.

套接字完全关闭后触发。参数 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'

  • ip <string> 套接字尝试连接的 IP。

    ¥ip <string> The IP which the socket is attempting to connect to.

  • port <number> 套接字尝试连接的端口。

    ¥port <number> The port which the socket is attempting to connect to.

  • family <number> IP 家族。对于 IPv6 可以是 6,对于 IPv4 可以是 4

    ¥family <number> The family of the IP. It can be 6 for IPv6 or 4 for IPv4.

当开始新的连接尝试时触发。如果在 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。

    ¥ip <string> The IP which the socket attempted to connect to.

  • port <number> 套接字尝试连接的端口。

    ¥port <number> The port which the socket attempted to connect to.

  • family <number> IP 家族。对于 IPv6 可以是 6,对于 IPv4 可以是 4

    ¥family <number> The family of the IP. It can be 6 for IPv6 or 4 for IPv4.

  • error <Error> 与失败相关的错误。

    ¥error <Error> The error associated with the failure.

连接尝试失败时触发。如果在 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'

  • ip <string> 套接字尝试连接的 IP。

    ¥ip <string> The IP which the socket attempted to connect to.

  • port <number> 套接字尝试连接的端口。

    ¥port <number> The port which the socket attempted to connect to.

  • family <number> IP 家族。对于 IPv6 可以是 6,对于 IPv4 可以是 4

    ¥family <number> The family of the IP. It can be 6 for IPv6 or 4 for IPv4.

连接尝试超时时触发。仅当在 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 将是 BufferString。数据编码由 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.

默认情况下(allowHalfOpenfalse)套接字将发送回传输结束数据包并在写完其待处理的写入队列后销毁其文件描述符。但是,如果 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'#

¥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.

事件:'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()#

返回操作系统报告的绑定 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#

稳定性: 0 - 已弃用:改用 writable.writableLength

¥Stability: 0 - Deprecated: Use writable.writableLength instead.

此属性显示为写入而缓冲的字符数。缓冲区可能包含编码后长度未知的字符串。所以这个数字只是缓冲区中字节数的近似值。

¥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:

这个函数是异步的。建立连接后,将触发 '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])#

在给定套接字上启动连接。通常不需要此方法,应使用 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()

    ¥autoSelectFamily <boolean>: If set to true, it enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. The all option passed to lookup is set to true and the sockets attempts to connect to all obtained IPv6 and IPv4 addresses, in sequence, until a connection is established. The first returned AAAA address is tried first, then the first returned A address, then the second returned AAAA address and so on. Each connection attempt (but the last one) is given the amount of time specified by the autoSelectFamilyAttemptTimeout option before timing out and trying the next address. Ignored if the family option is not 0 or if localAddress is set. Connection errors are not emitted if at least one connection succeeds. If all connections attempts fails, a single AggregateError with all failed attempts is emitted. Default: net.getDefaultAutoSelectFamily().

  • autoSelectFamilyAttemptTimeout <number> :使用 autoSelectFamily 选项时在尝试下一个地址之前等待连接尝试完成的时间量(以毫秒为单位)。如果设置为小于 10 的正整数,则将使用值 10。默认值:net.getDefaultAutoSelectFamilyAttemptTimeout()

    ¥autoSelectFamilyAttemptTimeout <number>: The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the autoSelectFamily option. If set to a positive integer less than 10, then the value 10 will be used instead. Default: net.getDefaultAutoSelectFamilyAttemptTimeout().

  • family <number> :IP 栈的版本。必须是 460。值 0 表示允许使用 IPv4 和 IPv6 地址。默认值:0

    ¥family <number>: Version of IP stack. Must be 4, 6, or 0. The value 0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.

  • hints <number> 可选 dns.lookup() 提示

    ¥hints <number> Optional dns.lookup() hints.

  • host <string> 套接字应连接到的主机。默认值:'localhost'

    ¥host <string> Host the socket should connect to. Default: 'localhost'.

  • keepAlive <boolean> 如果设置为 true,则它会在连接建立后立即在套接字上启用保持活动功能,类似于在 socket.setKeepAlive() 中所做的。默认值:false

    ¥keepAlive <boolean> If set to true, it enables keep-alive functionality on the socket immediately after the connection is established, similarly on what is done in socket.setKeepAlive(). Default: false.

  • keepAliveInitialDelay <number> 如果设置为正数,则它会设置在空闲套接字上发送第一个保持活跃探测之前的初始延迟。默认值:0

    ¥keepAliveInitialDelay <number> If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. Default: 0.

  • localAddress <string> 套接字应该连接的本地地址。

    ¥localAddress <string> Local address the socket should connect from.

  • localPort <number> 套接字应连接的本地端口。

    ¥localPort <number> Local port the socket should connect from.

  • lookup <Function> 自定义查找函数。默认值:dns.lookup()

    ¥lookup <Function> Custom lookup function. Default: dns.lookup().

  • noDelay <boolean> 如果设置为 true,则它会在套接字建立后立即禁用 Nagle 算法。默认值:false

    ¥noDelay <boolean> If set to true, it disables the use of Nagle's algorithm immediately after the socket is established. Default: false.

  • port <number> 必需的。套接字应连接到的端口。

    ¥port <number> Required. Port the socket should connect to.

对于 IPC 连接,可用的 options 是:

¥For IPC connections, available options are:

socket.connect(path[, connectListener])#

在给定套接字上启动 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])#

在给定的套接字上发起 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#

如果 truesocket.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])#

确保此套接字上不再发生 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> 指示连接是否被销毁。一旦连接被销毁,就无法使用它传输更多数据。

    ¥<boolean> Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.

有关详细信息,请参阅 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])#

半关闭套接字。即,它发送一个 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#

本地端口的数字表示。例如,8021

¥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()#

暂停数据读取。也就是说,不会触发 '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()#

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#

远程端口的数字表示。例如,8021。如果套接字被销毁(例如,如果客户端断开连接),则值可能是 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()#

通过发送 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()#

调用 socket.pause() 后恢复读取。

¥Resumes reading after a call to socket.pause().

socket.setEncoding([encoding])#

将套接字的编码设置为 可读流。有关详细信息,请参阅 readable.setEncoding()

¥Set the encoding for the socket as a Readable Stream. See readable.setEncoding() for more information.

socket.setKeepAlive([enable][, initialDelay])#

启用/禁用保持活动功能,并可选择在空闲套接字上发送第一个保持活动探测之前设置初始延迟。

¥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])#

启用/禁用 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 毫秒后超时。默认情况下 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()#

如果这是事件系统中唯一活动的套接字,则在套接字上调用 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])#

在套接字上发送数据。第二个参数指定字符串情况下的编码。它默认为 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.

有关详细信息,请参阅 Writablewrite() 方法。

¥See Writable stream write() method for more information.

socket.readyState#

此属性将连接状态表示为字符串。

¥This property represents the state of the connection as a string.

  • 如果流正在连接 socket.readyStateopening

    ¥If the stream is connecting socket.readyState is opening.

  • 如果流可读可写,则为 open

    ¥If the stream is readable and writable, it is open.

  • 如果流可读不可写,则为 readOnly

    ¥If the stream is readable and not writable, it is readOnly.

  • 如果流不可读写,则为 writeOnly

    ¥If the stream is not readable and writable, it is writeOnly.

net.connect()#

net.createConnection() 的别名。

¥Aliases to net.createConnection().

可能的语法有:

¥Possible signatures:

net.connect(options[, connectListener])#

net.createConnection(options[, connectListener]) 的别名。

¥Alias to net.createConnection(options[, connectListener]).

net.connect(path[, connectListener])#

net.createConnection(path[, connectListener]) 的别名。

¥Alias to net.createConnection(path[, connectListener]).

net.connect(port[, host][, connectListener])#

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' 事件的监听器一次。

¥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.connect() 函数是此函数的别名。

¥The net.connect() function is an alias to this function.

net.createConnection(options[, connectListener])#

有关可用选项,请参阅 new net.Socket([options])socket.connect(options[, connectListener])

¥For available options, see new net.Socket([options]) and socket.connect(options[, connectListener]).

其他选项:

¥Additional options:

以下是 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' }); 

以下是使用 portonread 选项的客户端示例。在这种情况下,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])#

启动 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])#

发起 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

      ¥allowHalfOpen <boolean> If set to false, then the socket will automatically end the writable side when the readable side ends. Default: false.

    • highWaterMark <number> 可选择覆盖所有 net.Socket' readableHighWaterMarkwritableHighWaterMark。默认值:参见 stream.getDefaultHighWaterMark()

      ¥highWaterMark <number> Optionally overrides all net.Sockets' readableHighWaterMark and writableHighWaterMark. Default: See stream.getDefaultHighWaterMark().

    • keepAlive <boolean> 如果设置为 true,则它会在接收到新的传入连接后立即在套接字上启用保持活动功能,类似于在 socket.setKeepAlive() 中所做的。默认值:false

      ¥keepAlive <boolean> If set to true, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, similarly on what is done in socket.setKeepAlive(). Default: false.

    • keepAliveInitialDelay <number> 如果设置为正数,则它会设置在空闲套接字上发送第一个保持活跃探测之前的初始延迟。默认值:0

      ¥keepAliveInitialDelay <number> If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. Default: 0.

    • noDelay <boolean> 如果设置为 true,则它会在收到新的传入连接后立即禁用 Nagle 算法。默认值:false

      ¥noDelay <boolean> If set to true, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. Default: false.

    • pauseOnConnect <boolean> 指示是否应在传入连接上暂停套接字。默认值:false

      ¥pauseOnConnect <boolean> Indicates whether the socket should be paused on incoming connections. Default: false.

  • connectionListener <Function> 自动设置为 'connection' 事件的监听器。

    ¥connectionListener <Function> Automatically set as a listener for the 'connection' event.

  • 返回:<net.Server>

    ¥Returns: <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 选项的当前默认值。

    ¥Returns: <boolean> The current default value of the autoSelectFamily option.

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

    ¥value <boolean> The new default value. The initial default value is true, unless the command line option --no-network-family-autoselection is provided.

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 选项的当前默认值。

    ¥Returns: <number> The current default value of the autoSelectFamilyAttemptTimeout option.

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 指定的值。

    ¥value <number> The new default value, which must be a positive number. If the number is less than 10, the value 10 is used instead. The initial default value is 250 or the value specified via the command line option --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 
Node.js 中文网 - 粤ICP备13048890号