net.createConnection(options[, connectListener])


有关可用选项,请参阅 new net.Socket([options])socket.connect(options[, connectListener])

【For available options, see new net.Socket([options]) and socket.connect(options[, connectListener]).】

其他选项:

【Additional options:】

以下是 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' }); 

以下是一个客户端使用 portonread 选项的示例。在这种情况下,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));
    },
  },
});