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:】
import net from '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');
});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' }); 以下是一个客户端使用 port 和 onread 选项的示例。在这种情况下,onread 选项将仅用于调用 new net.Socket([options]),而 port 选项将用于调用 socket.connect(options[, connectListener])。
【Following is an example of a client using the port and onread
option. In this case, the onread option will be only used to call
new net.Socket([options]) and the port option will be used to
call socket.connect(options[, connectListener]).】
import net from 'node:net';
import { Buffer } from 'node:buffer';
net.createConnection({
port: 8124,
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));
},
},
});const net = require('node:net');
net.createConnection({
port: 8124,
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));
},
},
});