What is net?
The 'net' npm package provides an asynchronous network API for creating stream-based TCP or IPC servers and clients. It is a core module in Node.js, allowing developers to build network applications with ease.
What are net's main functionalities?
Creating a TCP Server
This feature allows you to create a TCP server that listens for incoming connections on a specified port and IP address. The server can send and receive data from connected clients.
const net = require('net');
const server = net.createServer((socket) => {
socket.write('Hello from server!\n');
socket.on('data', (data) => {
console.log('Received:', data.toString());
});
});
server.listen(8080, '127.0.0.1', () => {
console.log('Server listening on port 8080');
});
Creating a TCP Client
This feature allows you to create a TCP client that connects to a specified server. The client can send and receive data from the server.
const net = require('net');
const client = net.createConnection({ port: 8080, host: '127.0.0.1' }, () => {
console.log('Connected to server!');
client.write('Hello from client!');
});
client.on('data', (data) => {
console.log('Received:', data.toString());
client.end();
});
client.on('end', () => {
console.log('Disconnected from server');
});
Handling Multiple Connections
This feature demonstrates how to handle multiple client connections on a TCP server. Each new connection is logged, and data can be sent and received from each client independently.
const net = require('net');
const server = net.createServer((socket) => {
console.log('New connection');
socket.write('Welcome!\n');
socket.on('data', (data) => {
console.log('Received:', data.toString());
});
socket.on('end', () => {
console.log('Connection closed');
});
});
server.listen(8080, '127.0.0.1', () => {
console.log('Server listening on port 8080');
});
Other packages similar to net
ws
The 'ws' package is a simple to use, blazing fast, and thoroughly tested WebSocket client and server for Node.js. Unlike 'net', which is for TCP connections, 'ws' is specifically designed for WebSocket connections, providing a higher-level protocol for real-time communication.
socket.io
The 'socket.io' package enables real-time, bidirectional, and event-based communication. It works on every platform, browser, or device, focusing equally on reliability and speed. While 'net' is for low-level TCP connections, 'socket.io' abstracts many complexities and provides a more user-friendly API for real-time web applications.
http
The 'http' package is a core Node.js module for creating HTTP servers and clients. While 'net' is used for TCP connections, 'http' is specifically designed for handling HTTP requests and responses, making it more suitable for web server development.