Linux Socket编程中的心跳机制(2)

int  recv_client_info(int client_sock,char* info,int length)
{
    int num;
    struct timeval tv;
    tv.tv_sec = 15;
    tv.tv_usec = 0;
    if (setsockopt(client_sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))>=0) {
        num = recv(client_sock,info,length,MSG_NOSIGNAL);
        if(num < 0) {
        perror("recv");
        return 0;
        } else if(num == 0) {
        printf("recv over\n");
        return -2;
        } else {
        pthread_mutex_lock(&mutex);
        TCP_Timeout = 0;
        pthread_mutex_unlock(&mutex);
        return 0;
        }
    } else {
        printf("TCP CONNECT超时...\n");
        return -1;
    }
}

第二种方法在Linux,Window2000下的实现Windows 2000平台下
头文件

#include <mstcpip.h>
//定义结构及宏
struct TCP_KEEPALIVE {
u_longonoff;
u_longkeepalivetime;
u_longkeepaliveinterval;
} ;
tcp_keepalive live,liveout; 
live.keepaliveinterval=500; 
live.keepalivetime=3000; 
live.onoff=TRUE; 
int iRet = setsockopt(Socket,SOL_SOCKET,SO_KEEPALIVE,(char *)Opt,sizeof(int)); 
if(iRet == 0){ 
    DWORD dw; 
    if(WSAIoctl(Socket,SIO_KEEPALIVE_VALS,&live,sizeof(live),&liveout,sizeof(liveout),&dw,NULL,NULL)== SOCKET_ERROR){ 
        //Delete Client 
        return; 
    } 

 ACE下代码
  int Opt = 1;
  //在测试过程中,发现检测的次数是5次,即下面的设置中,从最近一次消息开始计算的10秒后,每次间隔5秒,连续发送5次,即
  //35秒发现网络断了
tcp_keepalive live,liveout; 
live.keepaliveinterval=5000; //每次检测的间隔 (单位毫秒)
live.keepalivetime=10000;  //第一次开始发送的时间(单位毫秒)
live.onoff=TRUE; 
int iRet = stream.set_option(SOL_SOCKET,SO_KEEPALIVE,&Opt,sizeof(int)); 
if(iRet == 0){ 
  DWORD dw; 
  //此处显示了在ACE下获取套接字的方法,即句柄的(SOCKET)化就是句柄
  if(WSAIoctl((SOCKET)h,SIO_KEEPALIVE_VALS,&live,sizeof(live),&liveout,sizeof(liveout),&dw,NULL,NULL)== SOCKET_ERROR){ 
          //Delete Client 
          return; 
  } 

Linux平台下

#include    "/usr/include/linux/tcp.h"
#include "/usr/include/linux/socket.h"
////KeepAlive实现,单位秒
//下面代码要求有ACE,如果没有包含ACE,则请把用到的ACE函数改成linux相应的接口
int keepAlive = 1;//设定KeepAlive
int keepIdle = 5;//开始首次KeepAlive探测前的TCP空闭时间
int keepInterval = 5;//两次KeepAlive探测间的时间间隔
int keepCount = 3;//判定断开前的KeepAlive探测次数
if(setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,(void*)&keepAlive,sizeof(keepAlive)) == -1)
{
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%P|%t) setsockopt SO_KEEPALIVE error!n")));
}

if(setsockopt(s,SOL_TCP,TCP_KEEPIDLE,(void *)&keepIdle,sizeof(keepIdle)) == -1)
{
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%P|%t) setsockopt TCP_KEEPIDLE error!n")));
}

if(setsockopt(s,SOL_TCP,TCP_KEEPINTVL,(void *)&keepInterval,sizeof(keepInterval)) == -1)
{
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%P|%t) setsockopt TCP_KEEPINTVL error!n")));
}

if(setsockopt(s,SOL_TCP,TCP_KEEPCNT,(void *)&keepCount,sizeof(keepCount)) == -1)
{
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%P|%t)setsockopt TCP_KEEPCNT error!n")));
}

假设一种情况:一个socket TCP监听进程监听数据的时候如何接收关闭文件的socket连接?

不用并发

read/recv函数返回0均表示正常结束。此时关闭即可。如果用select/poll/epoll管理,该套接字也会读就绪,然后调用recv/read返回0。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/8c09cb2eebf68925ebca6490e88d6ba2.html