socket.connectSync(port[, address])
port<integer>address<string> 要连接的数字IP地址。与socket.connect()不同,不会进行DNS解析,因此不接受主机名。如果省略,则使用'127.0.0.1'(用于udp4套接字)或'::1'(用于udp6套接字)。
socket.connect() 的同步对应方法。对于 UDP 套接字,connect(2) 只记录默认的对端地址,并且是一个本地的、非阻塞的系统调用,因此关联是内联执行的。调用本身引发的任何错误(例如地址族不匹配时的 EAFNOSUPPORT)会同步抛出,而不是通过 'error' 事件报告。因为 connect(2) 不会探测可达性,所以诸如 ECONNREFUSED 之类的错误仍会在稍后的发送或接收中异步显现,这完全和 socket.connect() 一样:
🌐 The synchronous counterpart of socket.connect(). For a UDP socket
connect(2) only records the default peer address and is a local, non-blocking
system call, so the association is performed inline. Any error raised by the
call itself (for example EAFNOSUPPORT for a mismatched address family) is
thrown synchronously rather than reported via the 'error' event. Because
connect(2) does not probe reachability, errors such as ECONNREFUSED are
still surfaced asynchronously on a later send or receive, exactly as for
socket.connect():
const dgram = require('node:dgram');
const socket = dgram.createSocket('udp4');
socket.connectSync(41234, '127.0.0.1');
console.log(socket.remoteAddress()); // { address: '127.0.0.1', family: 'IPv4', port: 41234 } 如果套接字仍未绑定,它会先同步绑定。connectSync() 返回后,socket.remoteAddress() 会同步有效,并且 'connect' 事件会在下一个循环中触发。尝试在已经连接的套接字上调用 connectSync() 会抛出 ERR_SOCKET_DGRAM_IS_CONNECTED 异常,而在异步 socket.bind() 仍在进行中调用它则会抛出 ERR_SOCKET_ALREADY_BOUND 异常。
🌐 If the socket is still unbound it is bound synchronously first. After
connectSync() returns, socket.remoteAddress() is valid synchronously
and the 'connect' event is emitted on the next tick. Trying to call
connectSync() on an already connected socket throws an
ERR_SOCKET_DGRAM_IS_CONNECTED exception, and calling it while an
asynchronous socket.bind() is still in progress throws an
ERR_SOCKET_ALREADY_BOUND exception.
address 必须是数字 IP 字面量;connectSync() 从不执行 DNS 解析(异步名称解析是连接中唯一真正会阻塞的部分)。