类:net.BoundSocket


🌐 Class: net.BoundSocket

允许同步创建一个预绑定的套接字,这个套接字可以在之后传递给 listen()new net.Socket()。对于 listen() 来说,这可以实现同步端口保留,而对于 new net.Socket(),它允许通过 bind(2) 语义控制本地出口端口/IP。

🌐 Allows for the synchronous creation of a pre-bound socket, that can be passed to listen() or new net.Socket() later on. For listen() this enables synchronous port reservation, while for new net.Socket(), it allows control over the local egress port/IP, via bind(2) semantics.

BoundSocket 绑定 TCP 端点(hostport)或者 Unix 域/命名管道端点(path);两者互斥。对于 path,文件系统条目在构造函数中就已保留,所以像 EADDRINUSE 这样的冲突会像 TCP 绑定一样同步抛出。在 Linux 上,path 前面的 '\0' 会选择抽象命名空间(没有文件系统条目);在其他平台上,抽象路径会抛出 ERR_INVALID_ARG_VALUE

🌐 A BoundSocket binds either a TCP endpoint (host or port) or a Unix domain/named-pipe endpoint (path); the two are mutually exclusive. For a path, the file system entry is reserved in the constructor, so conflicts such as EADDRINUSE throw synchronously exactly as a TCP bind does. On Linux a leading '\0' in path selects the abstract namespace (no file system entry); an abstract path on any other platform throws ERR_INVALID_ARG_VALUE.

采纳会转移套接字的所有权;之后 address()close() 会抛出 ERR_SOCKET_HANDLE_ADOPTED。一个从未被采纳的句柄必须关闭,以避免套接字泄漏。关闭管道 BoundSocket 会移除它的文件系统条目;抽象绑定和 TCP 绑定没有条目需要移除。

🌐 Adoption transfers ownership of the socket; afterwards address() and close() throw ERR_SOCKET_HANDLE_ADOPTED. A handle that is never adopted must be closed to avoid leaking the socket. Closing a pipe BoundSocket removes its file system entry; abstract and TCP binds have none to remove.

当绑定到源 path 的管道 BoundSocket 被作为客户端采用时,一旦连接,该路径会被报告为套接字的 localAddress

🌐 When a pipe BoundSocket bound to a source path is adopted as a client, that path is reported as the socket's localAddress once it connects.

当一个被采用的 BoundSocket 连接到一个数字 IP 字面量时,connect(2) 会同步触发,所以 socket.localAddress 会在 socket.connect() 返回后被解析。连接失败仍然会通过延迟的 'error' 事件报告。

🌐 When an adopted BoundSocket connects to a numeric IP literal, connect(2) is issued synchronously, so socket.localAddress is resolved once socket.connect() returns. Connection failures are still reported via a deferred 'error' event.

import net from 'node:net';

const bound = new net.BoundSocket();
const { port } = bound.address();
console.log(`Reserved port ${port} for server`);

const server = net.createServer();
server.listen(bound); // Adopt as a server, or pass to new net.Socket() instead.