/* 仅列出主要头文件 */
#include
#include
#include
#include
#include
/* 调用方法
* sg_socketfd 为服务端的监听socket
*/
anetKeepAlive(NULL, sg_socketfd, 6);
/* TCP 心跳包检测 */
/* Set TCP keep alive option to detect dead peers. The interval option
* is only used for Linux as we are using Linux-specific APIs to set
* the probe send time, interval, and count. */
int ANET_ERR = -1;
int anetKeepAlive(char *err, int fd, int interval)
{
int val = 1;
/* 开启keepalive机制 */
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1)
{
perror("setsockopt SO_KEEPALIVE:");
return ANET_ERR;
}
/* Default settings are more or less garbage, with the keepalive time
* set to 7200 by default on Linux. Modify settings to make the feature
* actually useful. */
/* 开始首次KeepAlive探测前的TCP空闲时间
* Send first probe after interval. */
val = interval;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
perror("setsockopt TCP_KEEPIDLE: \n");
return ANET_ERR;
}
/* 两次KeepAlive探测间的时间间隔
* Send next probes after the specified interval. Note that we set the
* delay as interval / 3, as we send three probes before detecting
* an error (see the next setsockopt call). */
val = interval/3;
if (val == 0) val = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
perror("setsockopt TCP_KEEPINTVL: \n");
return ANET_ERR;
}
/* 判定断开前的KeepAlive探测次数
* Consider the socket in error state after three we send three ACK
* probes without getting a reply. */
val = 3;
if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
perror("setsockopt TCP_KEEPCNT: \n");
return ANET_ERR;
}
return 0;
}