TCP in node.js application

What is the TCP protocol ?

TCP (Transmission Control Protocol) is a transport layer protocol that is used to establish a reliable connection between two devices over a network. It is designed to ensure that data is delivered correctly to the receiving device by re transmitting any lost or damaged packets.

Example of TCP:

  1. Web browsing: When you access a website using your web browser, your device establishes a TCP connection to the web server. The web browser sends a request to the server using TCP, and the server responds by sending the requested webpage back to the browser using TCP.

  2. Email: When you send an email, your email client establishes a TCP connection to the email server. The email client sends the email message to the server using TCP, and the server then sends the message to the recipient's email server using TCP.

  3. File transfer: When you transfer a file from one device to another over a network, TCP is often used to ensure that the file is delivered correctly. For example, when you use a file-sharing program like Dropbox, a TCP connection is established between your device and the Dropbox server, and the file is transferred using TCP.

  4. Remote access: When you use a program like Remote Desktop to access another device remotely, a TCP connection is established between your device and the remote device. The program sends data back and forth between the two devices using TCP to display the remote desktop and allow you to control it.

Pros :

  • Reliability: TCP is designed to ensure that data is delivered correctly to the receiving device. It does this by retransmitting any lost or damaged packets and by acknowledging the receipt of each packet.

  • Flow control: TCP uses flow control to prevent the sender from overwhelming the receiver with too much data. It does this by sending window size updates to the sender, which tells the sender how much data it is allowed to send before receiving an acknowledgement.

  • Congestion control: TCP uses congestion control to prevent network overload. It does this by adjusting the rate at which it sends data based on the amount of available bandwidth and the number of packets that are being lost or delayed.

Cons :

  • Overhead: TCP adds a lot of overhead to each data packet in the form of headers and error checking information. This can make it less efficient than other protocols in terms of bandwidth usage.

  • Latency: The error checking and retransmission of lost packets can add latency to the connection. This can make it less suitable for real-time applications that require low latency, such as online gaming or voice over IP (VoIP).

  • Difficulty with NAT: TCP can have difficulty with Network Address Translation (NAT), which is a method used to allow multiple devices to share a single IP address. This can make it difficult to establish connections in some network configurations.

Example :

here is example in Cpp :

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cerr << "Error creating socket" << std::endl;
        return 1;
    }
    sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_port = htons(1234);
    inet_pton(AF_INET, "127.0.0.1", &address.sin_addr);
    if (bind(sock, (sockaddr*)&address, sizeof(address)) < 0) {
        std::cerr << "Error binding socket" << std::endl;
        return 1;
    }
    if (listen(sock, 5) < 0) {
        std::cerr << "Error listening for connections" << std::endl;
        return 1;
    }
    sockaddr_in client_address;
    socklen_t client_len = sizeof(client_address);
    int client_sock = accept(sock, (sockaddr*)&client_address, &client_len);
    if (client_sock < 0) {
        std::cerr << "Error accepting connection" << std::endl;
        return 1;
    }
    const char* data = "Hello, client!";
    int bytes_sent = send(client_sock, data, strlen(data), 0);
    if (bytes_sent < 0) {
        std::cerr << "Error sending data" << std::endl;
        return 1;
    }

    // Receive data from the client
    char buffer[1024];
    int bytes_received = recv(client_sock, buffer, 1024, 0);
    if (bytes_received < 0) {
        std::cerr << "Error receiving data" << std::endl;
        return 1;
    }
    std::cout << "Received: " << buffer << std::endl;
    close(client_sock);
    close(sock);

    return 0;
}

Here is example in Node.js :

const net = require('net');
const server = net.createServer((socket) => {
  socket.on('data', (data) => {
    console.log(`Received: ${data}`);
  });
  socket.write('Hello, client!\n');
});
server.listen(1234, '127.0.0.1');

Establish Connection in TCP:

One common way to establish a connection in TCP is through the use of a three-way handshake. In this method, the client sends a SYN (synchronize) message to the server, requesting that a connection be established. The server responds with a SYN-ACK (synchronize-acknowledgment) message, acknowledging the request and containing its own sequence number. The client then sends an ACK (acknowledgment) message back to the server, acknowledging receipt of the SYN-ACK message and containing the client's own acknowledgement number.

Another way to establish a connection in TCP is through the use of a four-way handshake. In this method, the client and server exchange SYN and SYN-ACK messages as in the three-way handshake, but they also exchange an additional message to confirm that the connection has been terminated. This is often used when one of the devices needs to gracefully close the connection, rather than simply dropping it.

There are also variations on these handshake methods that may be used in different situations. For example, the SYN message may be sent with additional options or flags to indicate specific requirements or preferences for the connection. The handshake process is an important part of the TCP protocol, as it ensures that the devices are ready to communicate and that the connection is established in a reliable and efficient manner.

Terminate Connection:

In the Transmission Control Protocol (TCP), a connection is closed by exchanging a series of messages called the connection termination process. When one side wants to close the connection, it sends a FIN message to the other side, which responds with an ACK message. The side that sent the FIN then waits for a FIN message from the other side, and responds with an ACK message. This completes the connection termination process.

Here is an example of how the connection termination process works:

  1. Host A wants to close the connection, so it sends a FIN message to Host B.

  2. Host B receives the FIN message and sends an ACK message to Host A to acknowledge receipt of the FIN.

  3. Host B sends a FIN message to Host A to close its end of the connection.

  4. Host A receives the FIN message and sends an ACK message to Host B to acknowledge receipt of the FIN.

At this point, the connection is closed and no more data can be transmitted between the two hosts.