net.createServer([options][, connectionListener])
options
<Object>connectionListener
<Function> 自动设置为'connection'
事件的监听器。- 返回: <net.Server>
创建新的 TCP 或 IPC 服务器。
有关更多信息,请参阅 'end'
事件和 RFC 1122(第 4.2.2.13 章节)。
如果 pauseOnConnect
设置为 true
,则与每个传入连接关联的套接字将被暂停,并且不会从其句柄读取数据。
这允许在进程之间传递连接,而原始进程不会读取任何数据。
要开始从暂停的套接字读取数据,则调用 socket.resume()
。
服务器可以是 TCP 服务器或 IPC 服务器,这取决于其 listen()
什么。
以下是 TCP 回显服务器的示例,它监听端口 8124 上的连接:
const net = require('net');
const server = net.createServer((c) => {
// 'connection' 监听器。
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
使用 telnet
对此进行测试:
$ telnet localhost 8124
要监听套接字 /tmp/echo.sock
:
server.listen('/tmp/echo.sock', () => {
console.log('server bound');
});
使用 nc
连接到 Unix 域套接字服务器:
$ nc -U /tmp/echo.sock
options
<Object>connectionListener
<Function> Automatically set as a listener for the'connection'
event.- Returns: <net.Server>
Creates a new TCP or IPC server.
If allowHalfOpen
is set to true
, when the other end of the socket
sends a FIN packet, the server will only send a FIN packet back when
socket.end()
is explicitly called, until then the connection is
half-closed (non-readable but still writable). See 'end'
event
and RFC 1122 (section 4.2.2.13) for more information.
If pauseOnConnect
is set to true
, then the socket associated with each
incoming connection will be paused, and no data will be read from its handle.
This allows connections to be passed between processes without any data being
read by the original process. To begin reading data from a paused socket, call
socket.resume()
.
The server can be a TCP server or an IPC server, depending on what it
listen()
to.
Here is an example of an TCP echo server which listens for connections on port 8124:
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
Test this by using telnet
:
$ telnet localhost 8124
To listen on the socket /tmp/echo.sock
:
server.listen('/tmp/echo.sock', () => {
console.log('server bound');
});
Use nc
to connect to a Unix domain socket server:
$ nc -U /tmp/echo.sock