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' 监听器
  console.log('已连接到服务器');
  client.write('你好世界!\r\n');
});
client.on('data', (data) => {
  console.log(data.toString());
  client.end();
});
client.on('end', () => {
  console.log('已从服务器断开');
});

如果要连接到 /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:

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