DEV Community

Cover image for TCP Pros and Cons with working example
Ishan Mishra
Ishan Mishra

Posted on

TCP Pros and Cons with working example

Backend Essentials-2 [TCP]


1. Overview

This article covers the basics of TCP(Transmission Control Protocol) in terms of its pros and cons. This article also provides the working example of TCP.

2. TCP

TCP is a transport protocol that is used on top of IP to ensure reliable transmission of packets. TCP includes mechanisms to solve many of the problems that arise from packet-based messaging, such as lost packets, out of order packets, duplicate packets, and corrupted packets.

Pros:
  1. Acknowledgement: To ensure that data is received successfully this header is used. After sending the data sender starts a timer and if receiver doesn't sends back the acknowledgement after the timer ends sender sends the packet again. This ensures no data loss.
  2. Guaranteed delivery.
  3. Connection Based: Client and server needs to establish a unique connection.
  4. Congestion Control: Data waits(if network is busy) and sent when network can handle it.
  5. Ordered Packets: TCP connections can detect out of order packets by using the sequence and acknowledgement numbers.
Cons:
  1. Larger Packets: Because of all the above features.
  2. Slower than UDP.
  3. Stateful.
  4. Server Memory(DOS): Because of statfullness server needs to store the connection information. If some low level client keeps on sending request to the server without doing any acknowledgement, than server keeps waiting and the data is stored in memory(until timeout) so server can eventually die if many of these clients sends request.

3. Code Example

Requirements: nodejs, code editor, telnet

const net = require("net");

const server = net.createServer(socket=>{
    socket.write("Hello\n");

    socket.on("data", data=>{
        console.log(data.toString())
    })
})

server.listen(8080);

Enter fullscreen mode Exit fullscreen mode

Run the script by executing following command

node <filename>.js
Enter fullscreen mode Exit fullscreen mode

Next step is to connect to the TCP server, for this execute the following command in a terminal

telnet localhost 8080
Enter fullscreen mode Exit fullscreen mode

and now a "Hello" message will be printed on terminal screen, type any message in terminal and it will be printed on server's console screen.

Alt Text

Alt Text


[1]: TCP vs UDP Crash Course[Hussein Nasser]

[2]: Transmission Control Protocol[Khan Academy]


Top comments (0)