net.createConnection(options[, connectListener])
options<Object> 必需。将同时传递给new net.Socket([options])调用和socket.connect(options[, connectListener])方法。connectListener<Function>net.createConnection()函数的通用参数。如果提供,将在返回的套接字上作为一次性监听器添加到'connect'事件。- 返回:<net.Socket> 用于启动连接的新创建的套接字。
有关可用选项,请参阅 new net.Socket([options]) 和 socket.connect(options[, connectListener])。
🌐 For available options, see
new net.Socket([options])
and socket.connect(options[, connectListener]).
其他选项:
🌐 Additional options:
timeout<number> 如果设置,将在创建套接字后但在开始连接之前用于调用socket.setTimeout(timeout)。
以下是 net.createServer() 节中描述的回声服务器的一个客户端示例:
🌐 Following is an example of a client of the echo server described
in the net.createServer() section:
const net = require('node:net');
const client = net.createConnection({ port: 8124 }, () => {
// 'connect' listener.
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
}); 要连接到套接字 /tmp/echo.sock:
🌐 To connect on the socket /tmp/echo.sock:
const client = net.createConnection({ path: '/tmp/echo.sock' });