Node.js Net Module
The Node.js net
module provides an asynchronous network API that can be used to create TCP or UNIX socket servers and clients. This module provides functionality for creating sockets, handling sockets read and write, establishing connection to other servers and listening to incoming connections. In this tutorial, we'll cover the basics of using the net
module in Node.js.
Syntax
This is the syntax for creating a TCP server using the net
module:
const net = require('net');
const server = net.createServer((socket) => {
// socket handling logic
});
server.listen(portNumber, () => {
console.log(`Server listening on port ${portNumber}`);
});
This is the syntax for creating a TCP client outside of the server:
const net = require('net');
const client = new net.Socket();
client.connect(portNumber, ipAddress, () => {
console.log(`Connected to server ${ipAddress}:${portNumber}`);
// client socket handling logic
});
Example
Let's create a very simple echo server that listens to incoming connections and echos back whatever is sent to it.
const net = require('net');
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
console.log(`Received ${data.length} bytes`);
console.log(`Data: ${data.toString()}`);
socket.write(`Echo: ${data}`);
});
socket.on('close', () => {
console.log('Connection closed');
});
socket.on('error', (error) => {
console.error(error);
});
});
server.listen(8080, () => {
console.log(`Server listening on port ${server.address().port}`);
});
Output
When you run the example code above, you will see the following output:
Server listening on port 8080
Client connected
Received 12 bytes
Data: Hello World
Client connected
Received 10 bytes
Data: Goodbye!
Connection closed
Connection closed
This is because we have two clients connecting to the server - the first sending a message, and then closing the connection; the second sending a message and then closing the connection. In both cases, the server echoes back what was sent to it.
Explanation
In the example code above, we defined a TCP server that listens on port 8080 for incoming connections. When a client connects to the server, the createServer
callback function is called with a new socket
object representing the connection.
We register three event handlers on the socket object: data
, close
, and error
. The data
event is triggered whenever data is received from the client. We log the length of the data, the data itself, and then write back the data to the client. The close
event is triggered whenever the client closes the connection, and the error
event is triggered whenever an error occurs.
Use
The net
module is useful for building low-level network communication applications such as chat applications, file transfer applications, or proxy servers.
Important Points
- When defining socket event handlers, make sure to handle errors to avoid crashing your application.
- A single server instance can handle multiple client connections.
- It is possible to create both TCP and Unix servers using the
net
module.
Summary
In this tutorial, we learned how to use the Node.js net
module to create TCP socket servers and clients. We covered the syntax, example, output, explanation, use, and important points of this module. With this knowledge, we can now create low-level network communication applications using Node.js.