Node.js net Module
Node.js's net The module is a core module for creating TCP- or IPC-based servers and clients. It provides asynchronous network programming capabilities and can be used to build various network applications, such as chat servers and proxy servers.
Main Function
- Create TCP servers and clients
- Create IPC (Inter-Process Communication) servers and clients
- Handle network connections and data transmission
- Manage the lifecycle of network connections
Basic Usage
Create a TCP Server
Example
const
net
=
require
(
'net'
)
;
// Create a TCP server
const
server
=
net.
createServer
(
(
socket
)
=>
{
console.
log
(
'Client connected'
)
;
// Receive client data
socket.
on
(
'data'
,
(
data
)
=>
{
console.
log
(
`Received data
:
$
{
data
}
`
)
;
socket.
write
(
`Server received
:
$
{
data
}
`
)
;
// Send data to the client
}
)
;
// Client disconnected
socket.
on
(
'end'
,
(
)
=>
{
console.
log
(
'Client disconnected'
)
;
}
)
;
}
)
;
// Listen on port 3000
server.
listen
(
3000
,
(
)
=>
{
console.
log
(
'Server is listening on port 3000'
)
;
}
)
;
Create a TCP Client
Example
const
net
=
require
(
'net'
)
;
// Create a client and connect to the server
const
client
=
net.
createConnection
(
{
port
:
3000
}
,
(
)
=>
{
console.
log
(
'Connected to server'
)
;
client.
write
(
'Hello Server!'
)
;
// Send data to the server
}
)
;
// Receive server data
client.
on
(
'data'
,
(
data
)
=>
{
console.
log
(
`Received server data
:
$
{
data
}
`
)
;
client.
end
(
)
;
// Disconnect
}
)
;
client.
on
(
'end'
,
(
)
=>
{
console.
log
(
'Disconnected from the server'
)
;
}
)
;
Core API Details
net.createServer([options][, connectionListener])
Create a new TCP or IPC server.
Parameters:
options: optional configuration objectallowHalfOpen: whether to allow half-open connections, defaults to falsepauseOnConnect: whether to pause the socket on connection, defaults to false
connectionListener: automatically set as a listener for the 'connection' event
net.createConnection(options[, connectListener])
Create a TCP connection to the specified port and host.
Common options:
port: the port to connect to (required)host: the host to connect to, defaults to 'localhost'localAddress: the local interface used to bind the network connectionfamily: IP protocol family (4 or 6)
Network Socket
net.Socket is the core class of the net module, representing a network connection.
Common Events
connect: emitted when a connection is successfully establisheddata: emitted when data is receivedend: emitted when the other end of the connection sends a FIN packettimeout: emitted when the connection times out due to inactivityerror: emitted when an error occursclose: emitted when the socket is fully closed
// 2022-01-01 00:00:00 GMT
write(data[, encoding][, callback]): send data on the socketend([data][, encoding]): half-close the socketdestroy(): ensure that no more I/O activity occurs on this socketpause(): pause reading dataresume(): resume reading data
Advanced applications
Handle Multiple Client Connections
Example
const
net
=
require
(
'net'
)
;
const
server
=
net.
createServer
(
(
socket
)
=>
{
// Set a unique ID for each connection
socket.
id
=
Date
.
now
(
)
;
console.
log
(
`Client $
{
socket.
id
}
connected`
)
;
socket.
on
(
'data'
,
(
data
)
=>
{
console.
log
(
`From client $
{
socket.
id
}
received data
:
$
{
data
}
`
)
;
// Broadcast the message to all clients
server.
getConnections
(
(
err
,
count
)
=>
{
if
(
count
1
)
{
socket.
write
(
`There are $
{
count
1
}
other clients online`
)
;
}
}
)
;
}
)
;
socket.
on
(
'end'
,
(
)
=>
{
console.
log
(
`Client $
{
socket.
id
}
disconnected`
)
;
}
)
;
}
)
;
server.
listen
(
3000
)
;
Timeout Handling
Example
const
server
=
net.
createServer
(
(
socket
)
=>
{
// Set the connection timeout to 5 minutes
socket.
setTimeout
(
5
60
1000
)
;
socket.
on
(
'timeout'
,
(
)
=>
{
console.
log
(
'Connection timed out, disconnecting'
)
;
socket.
end
(
)
;
}
)
;
}
)
;
Methods and Properties
| Function | Description |
|---|---|
| Create a server | net.createServer([options][, connectionListener]): used to create a TCP server that can listen for connection requests. |
| Connect to a Server | net.connect(options[, connectListener]) or net.createConnection(options[, connectListener]): used to connect to a specified server (create a client). |
| Socket Object | socket The object represents a connection to a TCP server or client and contains various methods for sending, receiving, and closing the connection. |
Method
| No. | Method & Description |
|---|---|
| 1 | net.createServer([options][, connectionListener]) |
| Create a TCP server. The connectionListener parameter automatically creates a listener for the 'connection' event. | |
| 2 | net.connect(options[, connectionListener]) |
返回一个新的 'net.Socket',并连接到指定的地址和端口。
当 socket 建立的时候,将会触发 'connect' 事件。 |
| 3 | net.createConnection(options[, connectionListener])
Create a TCP connection to port port and host host. host defaults to 'localhost'. | | 4 | net.connect(port[, host][, connectListener])
Create a TCP connection with port port and host host. host defaults to 'localhost'. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 5 | net.createConnection(port[, host][, connectListener])
Create a TCP connection with port port and host host. host defaults to 'localhost'. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 6 | net.connect(path[, connectListener])
Create a unix socket connection to path. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 7 | net.createConnection(path[, connectListener])
Create a unix socket connection to path. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 8 | net.isIP(input)
Check whether the input is an IP address. IPV4 returns 4, IPV6 returns 6, otherwise returns 0. | | 9 | net.isIPv4(input)
If the input address is IPV4, returns true, otherwise returns false. | | 10 | net.isIPv6(input)
If the input address is IPV6, returns true, otherwise returns false. |
net.Server
net.Server is usually used to create a TCP or local server.
| No. | Method & Description |
|---|---|
| 1 | server.listen(port[, host][, backlog][, callback]) |
| Listen for connections on the specified port port and host host. By default, host accepts direct connections from any IPv4 address (INADDR_ANY). When port is 0, a random port will be assigned. | |
| 2 | server.listen(path[, callback]) |
| Start a local socket server through a connection with the specified path. | |
| 3 | server.listen(handle[, callback]) |
| Connect through the specified handle. | |
| 4 | server.listen(options[, callback]) |
| Properties of options: port port, host host, and backlog, along with the optional callback function; they are called together in server.listen(port, [host], [backlog], [callback]). Also, the path parameter can be used to specify a UNIX socket. | |
| 5 | server.close([callback]) |
| The server stops accepting new connections while keeping existing ones. This is an asynchronous function; when all connections end, the server will close and the 'close' event will be emitted. | |
| 6 | server.address() |
| The operating system returns the bound address, protocol family name, and server port. | |
| 7 | server.unref() |
| If this is the only active server in the event system, calling unref will allow the program to exit. | |
| 8 | server.ref() |
| In contrast to unref, if this is the only server, calling ref on a server that was previously unrefed will not let the program exit (the default behavior). If the server has already been refed, calling ref again has no effect. | |
| 9 | server.getConnections(callback) |
| Asynchronously get the number of currently active connections on the server. This is only valid after the socket has been sent to a child process; the callback function has two parameters, err and count. |
Events
| No. | Event & Description |
|---|---|
| 1 | listening |
| Emitted after the server calls server.listen to bind. | |
| 2 | connection |
| Emitted when a new connection is created. socket is an instance of net.Socket. | |
| 3 | close |
| Emitted when the server closes. Note that if connections exist, this event will not be emitted until all connections are closed. | |
| 4 | error |
| Emitted when an error occurs. The 'close' event will be called directly by the following events. |
net.Socket
The net.Socket object is an abstraction of a TCP or UNIX socket. net.Socket instances implement a duplex stream interface. They can be used when a user creates a client (using connect()), or they can be created by Node and passed to the user via the connection server event.
Events
net.Socket events include:
| No. | Event & Description |
|---|---|
| 1 | lookup |
| This event is emitted after the domain name is resolved but before the connection is made. It does not apply to UNIX sockets. | |
| 2 | connect |
| Emitted when a socket connection is successfully established. | |
| 3 | data |
| Emitted when data is received. | |
| 4 | end |
| This event is emitted when the other end of the socket sends a FIN packet. | |
| 5 | timeout |
| Emitted when the socket times out due to idleness; it merely indicates that the socket has been idle. The user must manually close the connection. | |
| 6 | drain |
| Emitted when the write buffer is empty. Can be used to control uploads. | |
| 7 | error |
| Emitted when an error occurs. | |
| 8 | close |
| Emitted when the socket is fully closed. The had_error parameter is a boolean indicating whether the socket was closed due to a transmission error. |
property
net.Socket provides many useful properties to facilitate control of socket interactions:
| No. | Attribute & Description |
|---|---|
| 1 | socket.bufferSize |
| This property shows the number of bytes to be written to the buffer. | |
| 2 | socket.remoteAddress |
| The remote IP address as a string, for example: '74.125.127.100' or '2001:4860:a005::68'. | |
| 3 | socket.remoteFamily |
| The remote IP protocol family as a string, such as 'IPv4' or 'IPv6'. | |
| 4 | socket.remotePort |
| The remote port, as a number, for example: 80 or 21. | |
| 5 | socket.localAddress |
| The local interface to which the network connection is bound, the local IP address that the remote client is connecting to, as a string. For example, if you are listening on '0.0.0.0' and a client connects at '192.168.1.1', this value will be '192.168.1.1'. | |
| 6 | socket.localPort |
| The local port address, as a number. For example: 80 or 21. | |
| 7 | socket.bytesRead |
| The number of bytes received. | |
| 8 | socket.bytesWritten |
| The number of bytes sent. |
Method
| No. | Method & Description |
|---|---|
| 1 | new net.Socket([options]) |
| Construct a new socket object. | |
| 2 | socket.connect(port[, host][, connectListener]) |
| Specify port port and host host to create a socket connection. The host parameter defaults to localhost. Normally you do not need to use net.createConnection to open a socket. It is only used when you implement your own socket. | |
| 3 | socket.connect(path[, connectListener]) |
| Open a unix socket at the specified path. Normally you do not need to use net.createConnection to open a socket. It is only used when you implement your own socket. | |
| 4 | socket.setEncoding([encoding]) |
| Set encoding | |
| 5 | socket.write(data[, encoding][, callback]) |
| Send data on the socket. The second parameter specifies the string encoding, which defaults to UTF8. | |
| 6 | socket.end([data][, encoding]) |
| Half-close the socket. For example, it sends a FIN packet. The server may still be sending data. | |
| 7 | socket.destroy() |
| Ensure that there is no I/O activity on this socket. Only needed in error situations (handling errors, etc.). | |
| 8 | socket.pause() |
| Pause reading data. That is, the data event will no longer be emitted. Very useful for controlling uploads. | |
| 9 | socket.resume() |
| Resume reading data after calling pause(). | |
| 10 | socket.setTimeout(timeout[, callback]) |
| When the socket has been idle for more than timeout milliseconds, set the socket to a timed-out state. | |
| 11 | socket.setNoDelay([noDelay]) |
| Disable the Nagle algorithm. By default, TCP connections use the Nagle algorithm, buffering data before sending. Setting noDelay to true will send data immediately when socket.write() is called. noDelay defaults to true. | |
| 12 | socket.setKeepAlive([enable][, initialDelay]) |
| Disable/enable the keep-alive feature, and optionally set an initial delay before sending the first keep-alive probe on an idle socket. Defaults to false. Set initialDelay (in milliseconds) to specify the delay between the last data packet received and the first keep-alive probe. Setting initialDelay to 0 will retain the default (or previous) value. The default value is 0. | |
| 13 | socket.address() |
| The operating system returns the bound address, protocol family name, and server port. The returned object has 3 properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. | |
| 14 | socket.unref() |
| If this is the only active server in the event system, calling unref will allow the program to exit. If the server has already been unrefed, calling unref again has no effect. | |
| 15 | socket.ref() |
| In contrast to unref, if this is the only server, calling ref on a server that was previously unrefed will not let the program exit (the default behavior). If the server has already been refed, calling ref again has no effect. |
Example
Create a server.js file with the following code:
Example
var
net
=
require
(
'net'
)
;
var
server
=
net.
createServer
(
function
(
connection
)
{
console.
log
(
'client connected'
)
;
connection.
on
(
'end'
,
function
(
)
{
console.
log
(
'Client closed connection'
)
;
}
)
;
connection.
write
(
'Hello World!\r\n'
)
;
connection.
pipe
(
connection
)
;
}
)
;
server.
listen
(
8080
,
function
(
)
{
console.
log
(
'server is listening'
)
;
}
)
;
Execute the above server code:
$ node server.js
server is listening # 服务已创建并监听 8080 端口
Open a new window, create a client.js file with the following code:
Example
var
net
=
require
(
'net'
)
;
var
client
=
net.
connect
(
{
port
:
8080
}
,
function
(
)
{
console.
log
(
'Connected to server!'
)
;
}
)
;
client.
on
(
'data'
,
function
(
data
)
{
console.
log
(
data.
toString
(
)
)
;
client.
end
(
)
;
}
)
;
client.
on
(
'end'
,
function
(
)
{
console.
log
(
'Disconnect from the server'
)
;
}
)
;
Execute the above client code:
连接到服务器!
Hello World!
断开与服务器的连接
Gif Example Demonstration
Practical Application Scenarios
- Chat Applications: build a real-time chat server
- Game servers: handle multiplayer real-time interaction
- Proxy Server: forward client requests
- Custom protocols: implement specific application-layer protocols
- IoT device communication: communicate with embedded devices
Best Practices
- Error handling: always listen for the 'error' event
- Resource management: promptly close connections that are no longer in use
- Performance considerations: for high-concurrency scenarios, consider using a connection pool
- Safety: implement appropriate authentication and encryption mechanisms
- Logging: log important connection events and data
Example
// Example: complete error handling
server.
on
(
'error'
,
(
err
)
=>
{
console.
error
(
'Server error:'
,
err
)
;
}
)
;
client.
on
(
'error'
,
(
err
)
=>
{
console.
error
(
'Client error:'
,
err
)
;
}
)
;
By mastering the net module, you can build various powerful network applications, understand the underlying principles of network communication, and lay a solid foundation for learning more advanced network frameworks.
Node.js Built-in Modules