In Node.js, The Net module provides a set of asynchronous network functions for creating servers and clients.
It is part of the core modules and is commonly used for building networking applications such as TCP servers and clients.
Overview of some key functionalities provided by the net module:
The "net.createServer" method is used to create a "TCP" server. It takes a callback function that will be called when a client connects.
const net = require('net'); const server = net.createServer((socket) => { console.log('Client connected'); // Handle data from the client socket.on('data', (data) => { console.log(`Received data: ${data}`); }); // Handle the end of the connection socket.on('end', () => { console.log('Client disconnected'); }); }); // Listen on a 8000 port on localhost const PORT = 8000; server.listen(PORT, () => { console.log(`Server listening on http://localhost:${PORT}`); });
Server listening on 127.0.0.1:8000 Client connected Received data: Hello, server!
The "net.createConnection" method is used to create a TCP Client that can connect to a TCP Server.
const net = require('net'); const client = net.createConnection({ port: 8000, host: 'localhost' }, () => { console.log('Connected to client'); // Send data to the server client.write('Hello, server!'); }); // Handle data received from the server client.on('data', (data) => { console.log(`Received data from server: ${data}`); }); // Handle the end of the connection client.on('end', () => { console.log('Disconnected from server'); });
Connected to client
Both the server and client can emit error events, and it's important to handle these events to prevent crashes.
server.on('error', (err) => { console.error(`Server error: ${err}`); }); client.on('error', (err) => { console.error(`Client error: ${err}`); });
To stop the server, we can call its `close` method. This will close the server and stop it from accepting new connections.
server.close(() => { console.log('Server closed'); });
The 'connection' event is emitted when a new connection is established. The callback function receives a socket object representing the connection.
server.on('connection', (socket) => { console.log('New connection established'); });