What is TCP Protocol: Explanation, Example, and Use Cases
TCP (Transmission Control Protocol) is a core protocol of the internet that ensures reliable, ordered, and error-checked delivery of data between devices. It establishes a connection before sending data and manages data flow to avoid loss or duplication.How It Works
Think of TCP as a phone call between two computers. Before they start talking, they say hello and agree to communicate, which is called establishing a connection. Once connected, they send messages in order, and the receiver confirms each message was received correctly.
If a message gets lost or mixed up, TCP makes sure it is sent again. This way, the conversation stays clear and reliable, even if the network is busy or has problems.
Example
This example shows a simple TCP client connecting to a server, sending a message, and receiving a response.
import socket # Create a TCP socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # Connect to example server on port 80 s.connect(('example.com', 80)) # Send HTTP GET request s.sendall(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n') # Receive response data = s.recv(1024) print('Received:', data.decode())
When to Use
Use TCP when you need reliable communication where data must arrive complete and in order. It is ideal for web browsing, email, file transfers, and any application where missing or out-of-order data would cause problems.
For example, when you load a website, TCP ensures all parts of the page arrive correctly so it displays properly. It is less suited for real-time applications like video calls where speed matters more than perfect accuracy.
Key Points
- Connection-oriented: TCP sets up a connection before data transfer.
- Reliable delivery: It checks for errors and resends lost data.
- Ordered data: Data arrives in the same order it was sent.
- Flow control: TCP manages data speed to avoid overload.
- Used widely: Powers many internet services like web, email, and file sharing.