java linux 心跳机制,Linux 网络编程中之心跳机制应用

/* 仅列出主要头文件 */

#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值