The net module provides an asynchronous network API for creating TCP servers and clients. Here's how to use it.
Basic TCP Server#
Basic TCP Client#
Server with Multiple Clients#
Connection Options#
Unix Domain Sockets#
Message Protocol#
Connection Pool#
Graceful Shutdown#
TLS/SSL Wrapper#
Proxy Server#
Server Events#
Socket Properties#
Best Practices#
Connection Handling:
✓ Set timeouts
✓ Handle errors
✓ Clean up on close
✓ Use keep-alive
Message Protocol:
✓ Length-prefix messages
✓ Handle partial reads
✓ Validate input
✓ Use buffers efficiently
Performance:
✓ Disable Nagle when needed
✓ Use connection pools
✓ Limit connections
✓ Monitor memory
Avoid:
✗ Ignoring errors
✗ Memory leaks
✗ Unbounded buffers
✗ Missing timeouts
Conclusion#
The Node.js net module provides low-level TCP networking capabilities. Use net.createServer() for servers and net.createConnection() for clients. Handle data events carefully with proper buffering, implement message protocols for reliable communication, and always handle errors and cleanup. For secure connections, use the tls module with the same API patterns.