There are many articles on the Internet that TCP why the connection requires three times to shake hands, close the connection requires four times handshake, said a lot of principles, but let a lot of people difficult to understand.
In fact, there is only one sentence: TCP connection is between two endpoints, because the TCP connection is a reliable connection, so whether to establish a connection or close the connection, requires two endpoints to send the request and receive confirmation
Second, to understand the TCP channel is Full-duplex, can read and write data , understand this after understand why the connection requires four times to shake hands.
First of all three times to shake hands, to establish a connection does not involve reading and writing channels, only two endpoints of the request and confirmation. Remember that there are two endpoints between the two endpoints that are equal in relation to each other.
From the client's point of view, it only needs to send a request SYN, and then receive an ACK to know that the connection can be established
From the server-side point of view, it also only needs to send a request SYN, and then receive an ACK to know that the connection can be established
So set up a connection at least three times to shake hands, that is, the server received the client SYN, and then send an ACK to the client while carrying their own SYN, so that only need three times to shake hands can make both SYN and received ACK.
Of course, you can also use 4 or more handshakes when you design them, but at least 3 times.
When you close a connection, it is also two endpoints that send the request and receive confirmation. However, when the connection is closed, it involves the reading and writing channels of the two endpoints.
From the client's perspective, it sends a SHUTDOWN request fin and then receives an ACK to know that the connection can be closed
From the server's perspective, it sends a SHUTDOWN request fin and then receives an ACK to know that the connection can be closed
But because it's a read and write channel, so when the server side receives the client's shutdown fin, it may still send a message to the client, so you can only send an ACK to confirm that the client is closing the write channel, and that the service side cannot use a message to send it off the fin, only to wait for it to finish its own To resend a fin that closes the request.
So a handshake is a little more than a connection, and a minimum of 4 handshake is required to close the connection. It is not difficult to understand the concept of TCP semi-shutdown after understanding why you need to shake hands 4 times.