Android Interview: Network Essentials--Keepalive and Long Connection

Detailed explanation of long connection and keepalive

There are long connections and short connections in the TCP protocol. The short connection will disconnect itself after the data packet is sent, and the long connection will keep the connection for a certain period of time after the packet is sent, which is what we usually call the Keepalive (live timer) function.

The default Keepalive timeout requires 7,200,000 milliseconds, which is 2 hours, and the number of detections is 5 times. Its effect is the same as the heartbeat mechanism implemented by the user.

Keepalive works. On a given connection, if there is no activity within two hours, the server sends a probe segment to the client. (We will see what the detection segment looks like in the example below.)

The client host must be in one of the following four states:

1) The client host is still up and running and can be reached from the server. From the normal response of the client TCP, the server knows that the other party is still active. The server's TCP resets the liveness timer for the next two hours. If communication of the application occurs on the connection before the expiration of these two hours, the timer is reset for the next two hours again, and data is then exchanged.

 2) The client has crashed, or has been shut down (down), or is in the process of restarting. In both cases, its TCP will not respond. The server did not receive a response to its probe and timed out after 75 seconds. The server will send a total of 10 such probes, each for 75 seconds. If it does not receive a response, it assumes that the client host has closed and terminates the connection.

 3) The client has crashed, but it has been restarted. In this case, the server will receive a response to its survival detection, but the response is a reset, which causes the server to terminate the connection.

 4) The client host is actively running, but the slave server is not reachable. This is similar to state 2 because TCP cannot distinguish between the two. All it can show is that it has not received a response to its detection.

Linux provides two levels of configuration, kernel and socket.

The configuration of the kernel is:

net.ipv4.tcp_keepalive_time = 7200

net.ipv4.tcp_keepalive_intvl = 75

net.ipv4.tcp_keepalive_probes = 9

The socket configuration is:

setsockopt(..., TCP_KEEPIDLE, ...)

setsockopt(..., TCP_KEEPINTVL, ...)

setsockopt(..., TCP_KEEPCNT, ...)

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/cpcpcp123/article/details/115262990