net, dgram & DNS in nodejs
medium · Node.js — Server-side JavaScript
The net module in Node.js is the foundation for network communication. It allows you to create TCP (Transmission Control Protocol) servers and clients. Unlike the http module, which is a high-level protocol, net works at the Transport Layer , dealing with raw data streams. 1. What is TCP? TCP is a connection-oriented protocol that ensures reliable delivery of data. Three-way Handshake: Before sending data, the client and server "shake hands" to establish a connection. Reliability: It ensures data arrives in the correct order and re-transmits any lost packets. Streaming: Data is treated as a continuous stream of bytes. 2. Creating a TCP Server A TCP server listens for incoming connections from clients. Each connection is represented as a Socket , which is a Duplex Stream (you can both read from it and write to it). const net = require('net'); const server = net.createServer((socket) => { console.log('Client connected!'); // Listen for data from the client socket.on('data', (data) => { console.log(`Received: ${data.toString()}`); socket.write('Server acknowledged your message.\n'); }); socket.on('end', () => { console.log('Client disconnected.'); }); }); server.listen(8080, '127.0.0.1', () => { console.log('TCP Server started on port 8080'); }); 3. Creating a TCP Client The client initiates the connection to the server. const net = require('net'); const client = net.createConnection({ port: 8080 }, () => { console.log('Connected to server!'); client.write('Hello Server, this is the Client.'); }); client.on('data', (data) => { console.log(`Message from server: ${data.toString()}`); client.end(); // Close the connection after receiving the response }); 4. Key Socket Events Since a TCP socket is an EventEmitter , you use these events to manage the connection: connect : Emitted when a connection is successfully established. data : Emitted when data is received from the other side. end : Emitted when the other side signals it is done sending data (FIN packet). close : Emitted once the socket is fully closed. error : Crucial to catch—if a connection drops or fails, this event fires. 5. TCP vs. HTTP In your work as a developer, choosing between these two is about the level of control you need: Feature net (TCP) http Layer Transport Layer (Layer 4) Application Layer (Layer 7) Data Format Raw bytes/Buffers Headers + Body (Text-based) Efficiency Very high (low overhead) Lower (includes HTTP headers) Use Case Chat apps, IoT, Database drivers Websites, REST APIs 6. Real-World Use Cases Custom Protocols: If you were building a high-performance internal messaging system for a project s that didn't need the overhead of HTTP. Database Connection: Most database drivers (like the ones for MongoDB or PostgreSQL) use the net module under the hood to talk to the database server. Proxy Servers: Creating low-level load balancers that redirect traffic based on IP or port.