Author: a fish in water (powercc@21cn.com)
"Abnormal disconnection" indicates that TCP connections are not broken in an elegant way, such as the causes of network cable faults and other physical links, as well as sudden host power outages.
There are two methods to detect: 1. the TCP connection sends a handshake message at regular intervals. 2. Uses keepalive detection in the TCP protocol stack.
The second method is simple and reliable. You only need to set keepalive detection for two sockets connected to TCP. Therefore, this article only describes the second method in Linux, implementation in Windows (no further tests were conducted on other platforms)
Windows 2000
// Define the structure and macro
Struct tcp_keepalive {
U_longonoff;
U_longkeepalivetime;
U_longkeepaliveinterval;
};
# Define sio_keepalive_vals _ wsaiow (ioc_vendor, 4)
// Keepalive implementation
Tcp_keepalive inkeepalive = {0}; // enter the Parameter
Unsigned long ulinlen = sizeof (tcp_keepalive );
Tcp_keepalive outkeepalive = {0}; // output parameter
Unsigned long uloutlen = sizeof (tcp_keepalive );
Unsigned long ulbytesreturn = 0;
// Set the keep alive of the socket to 5 seconds and the number of sent requests to the socket to 3 times.
Inkeepalive. Onoff = 1;
Inkeepalive. keepaliveinterval = 5000; // interval between two keepalive probes
Inkeepalive. KeepAliveTime = 5000; // The tcp null close time before the first keepalive test starts.
If (wsaioctl (unsigned INT) s, sio_keepalive_vals,
(Lpvoid) & inkeepalive, ulinlen,
(Lpvoid) & outkeepalive, uloutlen,
& Ulbytesreturn, null, null) = socket_error)
{
Ace_debug (lm_info,
Ace_text ("(% p | % T)/wsaioctl failed. Error Code (% d )! /N "), wsagetlasterror ()));
}
Linux
# Include
......
//// Keepalive implementation
// BelowCodeAce is required. If Ace is not included, change the ace function used to the corresponding Linux interface.
Int keepalive = 1; // set keepalive
Int keepidle = 5; // tcp null close time before the first keepalive test is started
Int keepinterval = 5; // interval between two keepalive probes
Int keepcount = 3; // determines the number of keepalive probes before disconnection
If (setsockopt (S, sol_socket, so_keepalive, (void *) & keepalive, sizeof (keepalive) =-1)
{
Ace_debug (lm_info,
Ace_text ("(% p | % t) setsockopt so_keepalive error! /N ")));
}
If (setsockopt (S, sol_tcp, tcp_keepidle, (void *) & keepidle, sizeof (keepidle) =-1)
{
Ace_debug (lm_info,
Ace_text ("(% p | % t) setsockopt tcp_keepidle error! /N ")));
}
If (setsockopt (S, sol_tcp, tcp_keepintvl, (void *) & keepinterval, sizeof (keepinterval) =-1)
{
Ace_debug (lm_info,
Ace_text ("(% p | % t) setsockopt tcp_keepintvl error! /N ")));
}
If (setsockopt (S, sol_tcp, tcp_keepcnt, (void *) & keepcount, sizeof (keepcount) =-1)
{
Ace_debug (lm_info,
Ace_text ("(% p | % t) setsockopt tcp_keepcnt error! /N ")));