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

node server.js

2. Creating a TCP Client

A TCP client connects to a TCP server.

Example: Simple TCP Client


 


3. Important Socket Events

EventDescription
dataFired when data is received
endClient/server disconnects
connectTCP connection established
errorError occurs
timeoutConnection timeout

Example:


4. Writing Data to Socket

You can send strings, buffers, or JSON.


5. Using Encodings


6. Server Events

EventDescription
connectionFired when a client connects
errorServer error
closeServer shuts down
listeningServer 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

Featurenet Modulehttp Module
LevelLow-levelHigh-level
ProtocolTCPHTTP built over TCP
Use CaseRaw socket appsWebsites, APIs
DataBinary or textHTTP request/response

You may also like...