This code is derived from the basics and finishing cattle off the net book Introduction to C ++ interview,
URL https://www.nowcoder.com/tutorial/93/e1b14ab2b40a4ef98d9e55830eb48d66
TCP
Establish a connection and disconnection process:
establish connection:
Three-way handshake:
1. The client SYN flag bit is set to 1, a randomly generated value of the flag bit seq = i, the packet is sent to the server, the client enters the SYN_SENT state, waiting for the server to confirm.
2. After a server receives a packet SYN = 1 know the client requests to establish a connection, the server sends a SYN and ACK are set to 1, ack = i + 1, randomly generated seq = j, and the data packet to the client, enter SYN_RCVD state.
3. The client acknowledgment is received, check the ack = i + 1, ACK = 1, if correctly set the ACK 1, ack = j + 1, the packet is sent to the server, the server checks ack = j + 1, ACK = 1, if the proper connection is established.
Why three-way handshake:
Client has failed to prevent the connection request transmitted to B, an error is generated.
For example: the first client sends a request to send the request again after the timeout, the last two requests arrive at the server if no three-way handshake, two connections will be established, and only a valid connection, another connection will take up server resources . If a three-way handshake, the server does not receive a second request confirmation, it will not create a second connection.
Disconnect:
Four wave:
Full-duplex TCP connection, so in each direction to be closed separately.
1. The client sends a FIN packet, stops sending data into FIN_WAIT_1 state, then the client may further accept data.
2. After the server receives FIN packets, sends an ACK to the client, the server enters CLOSE_WAIT state, the client receives enter FIN_WAIT_2 state.
3. When the server has no data to transmit, transmits a FIN packet, the server state into the LAST-ACK, the client waits for acknowledgment.
4. The client FIN packet is received, it transmits the ACK packet, the client enters the TIME_WAIT state, waiting 2MSL (maximum survival time of the packet), and then closes the connection.