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])
。
其他选项:
timeout
<number> 如果设置,则将用于在创建套接字之后但在开始连接之前调用socket.setTimeout(timeout)
。
以下是 net.createServer()
部分中描述的回显服务器的客户端示例:
const net = require('net');
const client = net.createConnection({ port: 8124 }, () => {
// 'connect' 监听器。
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' });
options
<Object> Required. Will be passed to both thenew net.Socket([options])
call and thesocket.connect(options[, connectListener])
method.connectListener
<Function> Common parameter of thenet.createConnection()
functions. If supplied, will be added as a listener for the'connect'
event on the returned socket once.- Returns: <net.Socket> The newly created socket used to start the connection.
For available options, see
new net.Socket([options])
and socket.connect(options[, connectListener])
.
Additional options:
timeout
<number> If set, will be used to callsocket.setTimeout(timeout)
after the socket is created, but before it starts the connection.
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' });