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:

  • port <number> 必填。套接字应连接的端口。
  • host <string> 主机应连接到的套接字。默认值: 'localhost'
  • localAddress <string> 套接字应连接的本地地址。
  • localPort <number> 套接字应连接的本地端口。
  • family <number>IP 协议栈的版本。必须是 460。值 0 表示允许 IPv4 和 IPv6 地址。默认值: 0
  • hints <number> 可选 dns.lookup() 提示
  • lookup <Function> 自定义查找函数。默认: dns.lookup()
  • noDelay <boolean> 如果设置为 true,则在套接字建立后立即禁用 Nagle 算法。默认值: false
  • keepAlive <boolean> 如果设置为 true,则在连接建立后立即在套接字上启用保持连接功能,这与 socket.setKeepAlive([enable][, initialDelay]) 中所做的类似。默认值: false
  • keepAliveInitialDelay <number> 如果设置为正数,它会在空闲套接字上发送第一次保活探测之前设置初始延迟。默认值: 0

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

🌐 For IPC connections, available options are:

对于这两种类型,可用的 options 包括:

🌐 For both types, available options include:

  • onread <Object> 如果指定,传入的数据将存储在单个 buffer 中,并在数据到达套接字时传递给提供的 callback。这将导致流功能无法提供任何数据。套接字将像往常一样发出 'error''end''close' 等事件。像 pause()resume() 这样的方法也将按预期运行。
    • buffer <Buffer> | <Uint8Array> | <Function> 要么是一个可重复使用的内存块,用于存储传入的数据,要么是返回这样的内存块的函数。
    • callback <Function> 此函数会在每块传入数据到达时被调用。它会接收两个参数:写入到 buffer 的字节数,以及 buffer 的引用。从此函数返回 false 以隐式地 pause() 套接字。此函数将在全局上下文中执行。

以下是一个使用 onread 选项的客户端示例:

🌐 Following is an example of a client using the onread option:

const net = require('node:net');
net.connect({
  port: 80,
  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));
    }
  }
});