Three-way handshake

First handshake: The client sends a SYN packet (SYN = X) to the server and enters the SYN_SEND state for confirmation. (The packet segment does not contain application-layer data.)

Second handshake: After receiving a SYN packet, the server must acknowledge the client’s SYN (ACK = X +1) and send a SYN packet (ACK = Y). In this case, the server enters the SYN_RECV state. (The packet segment does not contain application-layer data.)

Third handshake: After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK = Y +1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state to complete the three-way handshake. (Can carry customer to server data in packet segment payload)

Ideally, once a TCP connection is established, it is maintained until either of the communicating parties voluntarily closes the connection.

Four times to wave

First wave: The active close sends a FIN and enters the FIN_WAIT_1 state. At this stage, data transmission from the active party to the passive party is closed, indicating that the active party will not transmit data to the passive party (of course, the active party will resend the data sent before the FIN packet if it does not receive the corresponding ACK message). However, the active party can still accept the data.

Second wave: After receiving the FIN packet, the passive close party sends an ACK to the peer party. The ACK sequence number is +1 (the same as SYN, one FIN occupies one SEQUENCE number). The passive close party enters the CLOSN_WAIT state, and the active close party enters the FIN_WAIT_2 state.

Third wave: The passive close sends a FIN and enters the LAST_ACK state. Used to turn off data transfer from passive closing party to active closing party, indicating that no more data will be sent.

Fourth wave: After receiving the FIN, the active closing party sends an ACK to the passive closing party, confirms that the serial number is received +1, and enters the TIME_WAIT state (the waiting time depends on the implementation). After waiting, the connection is officially closed. Thus, the four waves are completed.