原文
void socketkeepalive(int sockfd)
{
int keepAlive=1;//开启keepalive属性
int keepIdle=3;//如该连接在5秒内没有任何数据往来,则进行探测
int keepInterval=2;//探测时发包的时间间隔为2秒
int keepCount=3;//探测尝试的次数。如果第1次探测包就收到响应了,则后2次的不再发送
if(setsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,(void *)&keepAlive,sizeof(keepAlive))!=0)//若无错误发生,setsockopt()返回值为0
{
//启用心跳机制,如果您想关闭,将keepAlive置零即可
cout<<“It is SO_KEEPALIVE WRONG!”< exit(1);
}
if(setsockopt(sockfd,SOL_TCP,TCP_KEEPIDLE,(void *)&keepIdle,sizeof(keepIdle))!=0)
{
cout<<“It is TCP_KEEPIDLE WRONG!”< exit(1);
}
if(setsockopt(sockfd,SOL_TCP,TCP_KEEPINTVL,(void *)&keepInterval,sizeof(keepInterval))!=0)
{
cout<<“It is TCP_KEEPIDLE WRONG!”< exit(1);
}
if(setsockopt(sockfd,SOL_TCP,TCP_KEEPCNT,(void *)&keepCount,sizeof(keepCount))!=0)
{
cout<<“It is TCP_KEEPCNT WRONG!”< exit(1);
}
}
08-15
3322
05-20