Node.js Net Module
Here is a complete, beginner-friendly guide to the Node.js Net Module, explained with examples!
Node.js Net Module
The net module in Node.js allows you to create TCP servers and clients.
It is used for low-level networking operations—building chat servers, socket connections, proxies, IoT device communication, etc.
To use it:
1. Creating a TCP Server
A basic TCP server listens for client connections over a port.
Example: Simple TCP Server
Run server
2. Creating a TCP Client
A TCP client connects to a TCP server.
Example: Simple TCP Client
3. Important Socket Events
| Event | Description |
|---|---|
data | Fired when data is received |
end | Client/server disconnects |
connect | TCP connection established |
error | Error occurs |
timeout | Connection timeout |
Example:
4. Writing Data to Socket
You can send strings, buffers, or JSON.
5. Using Encodings
6. Server Events
| Event | Description |
|---|---|
connection | Fired when a client connects |
error | Server error |
close | Server shuts down |
listening | Server starts listening |
Example:
7. Broadcasting Messages (Chat Server Example)
A TCP chat server where all connected clients receive message.
8. Checking Client Address Details
9. Half-Open Connections
Enable half-open TCP connections:
10. Closing Server
11. Use Cases of Net Module
✔ Real-time chat applications
✔ Custom TCP protocols
✔ Proxy servers
✔ Multiplayer game servers
✔ IoT device communication
✔ Inter-process communication
12. Difference Between Net and HTTP
| Feature | net Module | http Module |
|---|---|---|
| Level | Low-level | High-level |
| Protocol | TCP | HTTP built over TCP |
| Use Case | Raw socket apps | Websites, APIs |
| Data | Binary or text | HTTP request/response |
