TCP Pros and Cons with working example
Ishan Mishra
Posted on July 24, 2021
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:
- 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.
- Guaranteed delivery.
- Connection Based: Client and server needs to establish a unique connection.
- Congestion Control: Data waits(if network is busy) and sent when network can handle it.
- Ordered Packets: TCP connections can detect out of order packets by using the sequence and acknowledgement numbers.
Cons:
- Larger Packets: Because of all the above features.
- Slower than UDP.
- Stateful.
- 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);
Run the script by executing following command
node <filename>.js
Next step is to connect to the TCP server, for this execute the following command in a terminal
telnet localhost 8080
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.
[1]: TCP vs UDP Crash Course[Hussein Nasser]
[2]: Transmission Control Protocol[Khan Academy]
Posted on July 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.