在服务器端打开keepalive功能
1、保证LWIP_TCP_KEEPALIVE被定义为1,(这样TCP_KEEPIDLE、TCP_KEEPINTVL和TCP_KEEPCNT 设置才有效)
2、
int32 keepalive = 1;
int32 keepidle = 1;
int32 keepinterval = 1;
int32 keepcount = 1;
int32 flag = 1;
if(setsockopt(server_socket, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(keepalive)) < 0)// 打开keepalive功能,需要在执行accept()之前执行
{
printf("set keepalive fail");
}
......accept()
setsockopt(accept_ret, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&keepidle , sizeof(keepidle));
setsockopt(accept_ret, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepinterval , sizeof(keepinterval));
setsockopt(accept_ret, IPPROTO_TCP, TCP_KEEPCNT, (void *)&keepcount , sizeof(keepcount));
setsockopt(accept_ret, IPPROTO_TCP, TCP_NODELAY, (void *)&flag , sizeof(flag));
在客户端打开keepalive功能(有些情况下keepalive不能正常工作,建议自建心跳包)
1、保证LWIP_TCP_KEEPALIVE被定义过
2、
int32 keepalive = 1;
int32 keepidle = 2;
int32 keepinterval = 2;
int32 keepcount = 2;
int32 flag = 1;
if(setsockopt(sta_socket, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(keepalive)) < 0)// 打开keepalive功能,需要在执行connect()之前执行
{
printf("set keepalive fail");
}
......connect()
setsockopt(sta_socket, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&keepidle , sizeof(keepidle));
setsockopt(sta_socket, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepinterval , sizeof(keepinterval));
setsockopt(sta_socket, IPPROTO_TCP, TCP_KEEPCNT, (void *)&keepcount , sizeof(keepcount));
setsockopt(sta_socket, IPPROTO_TCP, TCP_NODELAY, (void *)&flag , sizeof(flag));