现在的位置: 首页 > 综合 > 正文

Socket编程keepalive

2014年09月05日 ⁄ 综合 ⁄ 共 1417字 ⁄ 字号 评论关闭

 Linux

    #include

……

//KeepAlive实现

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)

{

    printf(“setsockopt SO_KEEPALIVE error!\n"”);

}

 

if(setsockopt(s,SOL_TCP,TCP_KEEPIDLE,(void *)&keepIdle,sizeof(keepIdle)) == -1)

{

    printf(“setsockopt TCP_KEEPIDLE error!\n"”);

}

 

if(setsockopt(s,SOL_TCP,TCP_KEEPINTVL,(void *)&keepInterval,sizeof(keepInterval)) == -1)

{

    printf(“setsockopt TCP_KEEPIDLE error!\n"”);

if (setsockopt(s, SOL_TCP, TCP_KEEPCNT, &val, sizeof(int)) != 0)
{
        return -1;
}

 

Windows2000

    //定义结构及宏

struct TCP_KEEPALIVE {

u_longonoff;

u_longkeepalivetime;

u_longkeepaliveinterval;

} ;

#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)

//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为5秒,并且发送次数为3次

inKeepAlive.onoff = 1;

inKeepAlive.keepaliveinterval = 5000; //两次KeepAlive探测间的时间间隔

inKeepAlive.keepalivetime = 5000; //开始首次KeepAlive探测前的TCP空闭时间

 

if (WSAIoctl((unsigned int)s, SIO_KEEPALIVE_VALS,

(LPVOID)&inKeepAlive, ulInLen,

(LPVOID)&outKeepAlive, ulOutLen,

&ulBytesReturn, NULL, NULL) == SOCKET_ERROR)

{

printf(“WSAIoctl failed.Error code(%d)!\r\n”,WSAGetLastError());

}

 

http://vrlinux.com/wenzhangjingxuan/20101027/78291_4.html

抱歉!评论已关闭.