Language: EN

comunicacion-tcp-nodejs

How to make TCP communications with Node.js and the NET module

  • 3 min

In Node.js, we can use the net module to create TCP servers and clients easily.

The TCP protocol provides a stable and reliable way to transmit data over the web, ensuring the ordered and error-free delivery of packets.

Some of its features are:

  • Stability: TCP establishes persistent connections between the client and the server, ensuring the ordered and error-free delivery of transmitted data.
  • Reliability: The acknowledgment mechanism for packet receipt ensures that TCP guarantees that data reaches its destination intact and in the correct order.
  • Congestion Control: TCP includes congestion control algorithms that regulate the flow of data between the endpoints of the connection.

TCP communication is used in a wide range of web applications, from file transfers to secure internet browsing.

Example of TCP Implementation in Node.js

Basic TCP Server

To create a basic TCP server in Node.js, we can use the net module. The following example shows how to create a TCP server that listens on a specific port and handles incoming connections:

import net from 'node:net';

// Create TCP server
const server = net.createServer((socket) => {
  console.log('Client connected');

  // Event when receiving data from the client
  socket.on('data', (data) => {
    console.log('Data received:', data.toString());

    // Send data back to the client
    socket.write('Data received by the server: ' + data.toString());
  });

  // Event when the client connection is closed
  socket.on('close', () => {
    console.log('Client disconnected');
  });

  // Handle connection errors
  socket.on('error', (err) => {
    console.error('Connection error:', err);
  });
});

const port = 3000;
server.listen(port, () => {
  console.log(`TCP server started on port ${port}`);
});

In this example:

  • A TCP server is created that listens on port 3000.
  • When a client connects, a message is printed to the console.
  • When the server receives data from the client, it prints it to the console and sends a response to the client.
  • When a client disconnects, a message is printed to the console.

To test this TCP server, you will need a client that can connect and send data. You can use a tool like telnet in the command line or write a client in JavaScript to test it 👇

TCP Client in Node.js

To connect to a TCP server from a client in Node.js, we can also use the net module. The following example shows how to create a TCP client that connects to a server on a specific host and port:

import net from 'node:net';

const client = new net.Socket();

const port = 3000;
const host = 'localhost'; // Change to the host where the server is

client.connect(port, host, () => {
  console.log('Connected to TCP server');
  client.write('Hello from the TCP client');
});

client.on('data', (data) => {
  console.log('Data received from server:', data.toString());
  client.end();
});

client.on('close', () => {
  console.log('Connection closed');
});

client.on('error', (err) => {
  console.error('Connection error:', err);
});

This TCP client will connect to the server we created earlier and send a message. When the server receives the message, it will print it to the console and send a response back to the client, which will also be printed in the client’s console.

To test it,

  • Run the Node.js server
  • Run the Node.js client.
  • You should see that the client connects to the server, sends a message, receives a response from the server, and then disconnects.

Download the Code

All the code from this post is available for download on Github github-full