What is Three Way Handshake TCP: Explained Simply
three way handshake in TCP is a process used to establish a reliable connection between two devices before data transfer. It involves three steps: the client sends a SYN, the server replies with SYN-ACK, and the client responds with ACK to confirm the connection.How It Works
The TCP three way handshake is like a polite conversation between two computers to start talking safely. Imagine you want to call a friend: first, you say "Hello, can we talk?" (this is the SYN message). Your friend replies, "Hello, I am ready to talk!" (this is the SYN-ACK message). Finally, you say "Great, let's start!" (this is the ACK message). Only after this exchange do both sides start sending real information.
This process ensures both devices agree on the connection and are synchronized, which helps avoid lost or mixed-up messages. It also sets up initial sequence numbers that keep track of the data sent and received, making the communication reliable.
Example
This Python example simulates the three way handshake steps using simple print statements to show the message flow between a client and a server.
class TCPConnection: def __init__(self): self.state = 'CLOSED' def client_send_syn(self): print('Client: Sending SYN') self.state = 'SYN_SENT' def server_receive_syn(self): if self.state == 'CLOSED': print('Server: Received SYN, sending SYN-ACK') self.state = 'SYN_RECEIVED' def client_receive_syn_ack(self): if self.state == 'SYN_SENT': print('Client: Received SYN-ACK, sending ACK') self.state = 'ESTABLISHED' def server_receive_ack(self): if self.state == 'SYN_RECEIVED': print('Server: Received ACK, connection established') self.state = 'ESTABLISHED' # Simulate handshake connection = TCPConnection() connection.client_send_syn() connection.server_receive_syn() connection.client_receive_syn_ack() connection.server_receive_ack()
When to Use
The three way handshake is used every time a TCP connection is established between two devices on a network. It is essential for applications that require reliable communication, such as web browsing, email, file transfers, and online gaming.
By confirming both sides are ready and synchronized, it prevents errors and data loss during communication. Without this handshake, devices might send data to each other without knowing if the other side is prepared, leading to confusion and dropped messages.
Key Points
- The three way handshake establishes a reliable TCP connection.
- It involves three messages: SYN, SYN-ACK, and ACK.
- It synchronizes sequence numbers for data transfer.
- It ensures both devices are ready before sending data.
- Used in most internet communications requiring reliability.