In the process of using TCP connection to transmit data, the client and server need to go through three-way handshake establishment Connection and four-way handshake disconnect operations.
The details are shown in the picture below
The above figure describes the detailed process of TCP connection from establishment to disconnection. The specific message details will be discussed below.
During the TCP three-way handshake to establish a connection, the client first sends a SYN=1, Sequence=p request packet to the server.
If the server agrees to grant the client the link, it sends a response packet of ACK=p 1, SYN=1, Sequence=q.
Finally, after the client receives the response packet from the server, it will also send a response packet to the server. The specific content is ACK=q 1, SYN=0, Sequence=p 1.
For TCP disconnection, a four-way handshake is required. Why not a three-way handshake? The specific reasons are:
When the Server receives the SYN connection request message from the Client, it can directly send the SYN ACK message. The ACK message is used for response, and the SYN message is used for synchronization. But when closing the connection, when the server receives the FIN message, it is likely that the SOCKET will not be closed immediately, so it can only reply with an ACK message first, telling the client, "I received the FIN message you sent." Only when all the messages on my server side have been sent can I send the FIN message, so it cannot be sent together. Therefore, a four-step handshake is required.
The disconnection process is initiated by the client first. First, the client will send a disconnection request packet with FIN=1, Sequence=m.
After receiving the request, the server will send a confirmation packet ACK=m 1, Sequence=n.
At this time, the unilateral connection from the client to the server has been disconnected, and the client will no longer send data packets to the server. The server can still send data to the client. If the server does not need to send data to the client after sending s data packets, it can send a disconnect request to the client at this time. FIN=1, Sequence=m s, ACK=m 1.
After receiving the server’s disconnect request, the client will send a confirmation packet. Sequence=m 1,ACK=m s 1;
Note that after the client sends the last ACK packet, it will still wait for 2MSL (maximum segment survival time), because the packet may be lost in the network, and the client waits for 2MSL because it is worried about the server. No ACK packet is received, so the FIN request is resent.