Learn how to create a basic TCP echo server using Node.js ’net’ module, ideal for understanding TCP communication and testing network connections.
javascript
// Importing the 'net' module to create TCP servers
const net = require('net');
// Defining the port on which the server will listen
const PORTA = 1337;
// Creating the TCP server
const server = net.createServer((socket) => {
// Log when a client connects
console.log('Client connected:', socket.remoteAddress + ':' + socket.remotePort);
// Event: data received from the client
socket.on('data', (data) => {
console.log('Data received from client:', data.toString());
// Echo: send back the received data
socket.write(data);
});
// Event: client closes the connection
socket.on('end', () => {
console.log('Client disconnected:', socket.remoteAddress + ':' + socket.remotePort);
});
// Handling socket errors
socket.on('error', (err) => {
console.error('Socket error:', err.message);
});
});
// Starting the server and listening on the defined port
server.listen(PORTA, () => {
console.log(`TCP server listening on port ${PORTA}`);
});
// Handling general server errors
server.on('error', (err) => {
console.error('Server error:', err.message);
});Node.js installed (version 12 or higher recommended)
Node.js 'net' module (built-in, no additional installation needed)
TCP port configuration (e.g., 1337) for server listening
TCP client for testing (e.g., netcat, telnet, or a custom client)
No external hardware required (software environment only)
Firewall configuration: ensure the chosen TCP port is open for incoming connections