当服务端开启心跳,客户端开启心跳,则当客户端意外断开连接,服务端释放连接,客户端释放连接
当服务端关闭心跳,客户端开启心跳,则当客户端意外断开连接,服务端不会知道,资源不会释放。而当客户端再一次向服务端请求连接的时候,服务端才会释放之前的socket
linux :
socket 配置
int optval;
socklen_t optlen = sizeof(optval);
optval = 1;
setsockopt(clt_sock, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen);
optval = 5;
setsockopt(clt_sock, SOL_TCP, TCP_KEEPCNT, &optval, optlen);
optval = 1;
setsockopt(clt_sock, SOL_TCP, TCP_KEEPIDLE, &optval, optlen);
optval = 1;
setsockopt(clt_sock, SOL_TCP, TCP_KEEPINTVL, &optval, optlen);
echo 600 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 60 > /proc/sys/net/ipv4/tcp_keepalive_intvl
echo 6 > /proc/sys/net/ipv4/tcp_keepalive_probes
windows:
socket 配置
int Opt=1;
TCP_KEEPALIVE live,liveout;
live.keepaliveinterval=500;
live.keepalivetime=3000;
live.onoff=TRUE;
int iRet = setsockopt(serSocket,SOL_SOCKET,SO_KEEPALIVE,(char *)Opt,sizeof(int));
if(iRet == 0){
DWORD dw;
if(WSAIoctl(serSocket,SIO_KEEPALIVE_VALS,
&live,sizeof(live),&liveout,sizeof(liveout),
&dw,NULL,NULL)== SOCKET_ERROR){
//Delete Client
return 0;
}
}