agent.createConnection(options[, callback])


  • options <Object> 包含连接详细信息的选项。请查看 net.createConnection() 以了解选项的格式。对于自定义代理,此对象将传递给自定义 createConnection 函数。

    ¥options <Object> Options containing connection details. Check net.createConnection() for the format of the options. For custom agents, this object is passed to the custom createConnection function.

  • callback <Function> (可选,主要用于自定义代理)自定义 createConnection 实现创建套接字时要调用的函数,尤其适用于异步操作。

    ¥callback <Function> (Optional, primarily for custom agents) A function to be called by a custom createConnection implementation when the socket is created, especially for asynchronous operations.

  • 返回:<stream.Duplex> 已创建的套接字。此值由默认实现或自定义同步 createConnection 实现返回。如果自定义 createConnection 使用 callback 进行异步操作,则此返回值可能不是获取套接字的主要方式。

    ¥Returns: <stream.Duplex> The created socket. This is returned by the default implementation or by a custom synchronous createConnection implementation. If a custom createConnection uses the callback for asynchronous operation, this return value might not be the primary way to obtain the socket.

生成用于 HTTP 请求的套接字/流。

¥Produces a socket/stream to be used for HTTP requests.

默认情况下,此函数的行为与 net.createConnection() 完全相同,同步返回创建的套接字。此默认实现不使用签名中的可选参数 callback

¥By default, this function behaves identically to net.createConnection(), synchronously returning the created socket. The optional callback parameter in the signature is not used by this default implementation.

但是,自定义代理可以重写此方法以提供更大的灵活性,例如,异步创建套接字。重写 createConnection 时:

¥However, custom agents may override this method to provide greater flexibility, for example, to create sockets asynchronously. When overriding createConnection:

  1. 同步套接字创建:重写方法可以直接返回套接字/流。

    ¥Synchronous socket creation: The overriding method can return the socket/stream directly.

  2. 异步套接字创建:重写方法可以接受 callback 并将创建的套接字/流传递给它(例如,callback(null, newSocket))。如果在创建套接字期间发生错误,则应将其作为第一个参数传递给 callback(例如,callback(err))。

    ¥Asynchronous socket creation: The overriding method can accept the callback and pass the created socket/stream to it (e.g., callback(null, newSocket)). If an error occurs during socket creation, it should be passed as the first argument to the callback (e.g., callback(err)).

代理将使用 options 和内部 callback 调用提供的 createConnection 函数。代理提供的 callback 具有 (err, stream) 的签名。

¥The agent will call the provided createConnection function with options and this internal callback. The callback provided by the agent has a signature of (err, stream).