Most CS applications require a heartbeat mechanism. The heartbeat mechanism is generally implemented on both the server and client, and the two have the same implementation principle. The client does not care about performance.
If the application is TCP-based, you can simply achieve heartbeat through so_keepalive. When the keepalive timer is set, TCP sends a TCP segment check to the peer. If no ACK or RST is received, after several attempts, the peer is deemed to be nonexistent and the application is notified.Program. The disadvantage here is that the server actively sends detection packets, which has a slight impact on performance.
Application Implementation
The client starts a timer and keeps sending heartbeat;
The server returns a response after receiving the heartbeat;
The server starts a timer to determine whether the client exists. Two methods are listed here: Time Difference and simple sign.
1. Time Difference Policy
After receiving a heartbeat, record the current time (recorded as recvedtime ).
Determine the time when the timer arrives, and calculate the time when the heartbeat is not received (t) = Current Time-recvedtime (the time recorded above ). If t is greater than a specified value, the client times out.
2. Simple flag
After receiving a heartbeat, set the connection flag to true;
Determine the time when the timer arrives and view all the signs. If it is false, the peer is deemed to have timed out. If it is true, set it to false.
The above method is simpler than above, but the error of detecting whether a client is offline is a little large.