类: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.
采纳会转移套接字的所有权;之后 address() 和 close() 会抛出 ERR_SOCKET_HANDLE_ADOPTED。一个从未被采纳的句柄必须被关闭,以避免套接字泄漏。
🌐 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.
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.