标签:
5如果客户端的超时定时器超时,依然没有收到应答包,则说明服务器挂了
转自:http://blog.sina.com.cn/s/blog_a459dcf5010153m5.html
根据上面的介绍我们可以知道对端以一种非优雅的方式断开连接的时候,我们可以设置SO_KEEPALIVE属性使得我们在2小时以后发现对方的TCP连接是否依然存在。
具体操作:
//设置KeepAlive
1、 BOOL bKeepAlive = TRUE;
int nRet=::setsockopt(sockClient,SOL_SOCKET,SO_KEEPALIVE,(char*)&bKeepAlive,sizeof(bKeepAlive));
if(nRet!=0)
{
AfxMessageBox("出错");
return ;
}
2、感觉两小时时间太长可以自行设定方法1
//设置KeepAlive检测时间和次数
tcp_keepalive inKeepAlive = {0}; //输入参数
unsigned long ulInLen = sizeof(tcp_keepalive );
tcp_keepalive outKeepAlive = {0}; //输出参数
unsigned long ulOutLen = sizeof(tcp_keepalive );
unsigned long ulBytesReturn = 0;
//设置socket的keep alive为10秒,并且发送次数为3次
inKeepAlive.onoff = 1;
inKeepAlive.keepaliveinterval = 4000; //两次KeepAlive探测间的时间间隔
inKeepAlive.keepalivetime = 1000; //开始首次KeepAlive探测前的TCP空闭时间
nRet=WSAIoctl(sockClient,
SIO_KEEPALIVE_VALS,
(LPVOID)&inKeepAlive,
ulInLen,
(LPVOID)&outKeepAlive,
ulOutLen,
&ulBytesReturn,
NULL,
NULL);
if(SOCKET_ERROR == nRet)
{
AfxMessageBox("出错");
return;
}
3、感觉两小时时间太长可以自行设定方法2
因此我们可以得到
int keepIdle = 6;
int keepInterval = 5;
int keepCount = 3;
Setsockopt(listenfd, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle));
Setsockopt(listenfd, SOL_TCP,TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
Setsockopt(listenfd,SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
详见:http://blog.csdn.net/gavin1203/article/details/5290609
对setsockopt的操作,详见:http://www.cnblogs.com/hateislove214/archive/2010/11/05/1869886.html
标签:
原文地址:http://www.cnblogs.com/stephen-init/p/4331577.html