Node.js Net Module: TCP Sockets
Node.js comes with powerful networking via the built-in net module. Using TCP sockets, you can build chat systems, messaging platforms, or any app needing two-way communication between clients and servers.
Node.js Tutorial:-
Complete Python Course:-
Server Code
// net_server.js
const net = require('net');
const server = net.createServer((socket) => {
socket.end('goodbye
');
}).on('error', (err) => {
throw err;
});
server.listen(50302, () => {
console.log('Server listening on port', 50302);
});
Client Code
// net_client.js
const net = require('net');
const client = net.connect({ port: 50302 }, () => {
console.log('Connected to server!');
client.write('world!
');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('Disconnected from server');
});
Run It
# Terminal 1
node net_server.js
# Terminal 2
node net_client.js
Important Notes
- Both server and client must use the same port.
- Handle
error,data,end, andcloseevents for robustness. - For HTTP, use the
httpmodule instead ÔÇönetis for raw TCP.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
The Node.js net module is your gateway to TCP socket programming. With just a few lines you can build real-time messaging and custom protocols. For more guides, stay tuned to .
node js net socket example
node js net module
node js net example
nodejs tcp server
node js net socket error handling
tcp server in nodejs
nodejs socket programming
net cat for node