net.createConnection(options[, connectListener])


可选的选项,查看 new net.Socket([options])socket.connect(options[, connectListener])

附加的选项:

下面是在 net.createServer() 章节描述的 server 的客户端示例:

const net = require('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,第二行只需要改为:

const client = net.createConnection({ path: '/tmp/echo.sock' });

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

Additional options:

Following is an example of a client of the echo server described in the net.createServer() section:

const net = require('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');
});

To connect on the socket /tmp/echo.sock the second line would just be changed to:

const client = net.createConnection({ path: '/tmp/echo.sock' });