golang:golang判断tcp是否断开的方法

 所属分类:php教程

 浏览:332次-  评论: 0次-  更新时间:2022-09-30
描述:更多教程资料进入php教程获得。 php入门到就业线上直播课:进入学习API 文档、设计、调试、自动化测试一体化协作工具:点击使用golang判断...
更多教程资料进入php教程获得。

php入门到就业线上直播课:进入学习
API 文档、设计、调试、自动化测试一体化协作工具:点击使用

golang判断tcp是否断开的方法:

keepalive检测,对于设置了keepalive来说,当tcp检测到对端socket不再可用时(不能发出探测包,或探测包没有收到ACK的响应包),select会返回socket可读,并且在recv时返回-1,同时置上errno为ETIMEDOUT。此时TCP的状态是断开的。

struct TCP_KEEPALIVE {  
    unsigned long onoff;  
    unsigned long keepalivetime;  
    unsigned long keepaliveinterval;  
} ;  
  
#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)  
  
/* KeepAlive实现 */  
void set_keepalive (SOCKET s)  
{  
    BOOL bKeepAlive = TRUE;  
    int nRet = ::setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char*)&bKeepAlive, sizeof(bKeepAlive));  
    if (nRet == SOCKET_ERROR)  
    {  
        return ;  
    }  
    /* 输入参数 */  
    struct TCP_KEEPALIVE inKeepAlive = {0};   
    unsigned long ulInLen = sizeof(struct TCP_KEEPALIVE);  
  
    /* 输出参数 */  
    struct TCP_KEEPALIVE outKeepAlive = {0};   
    unsigned long ulOutLen = sizeof(struct TCP_KEEPALIVE);  
    unsigned long ulBytesReturn = 0;  
    int ret = 0;  
  
    /* 设置keepalive 为5秒,并且发送次数为3次 */  
    inKeepAlive.onoff             = 1;  
    /* 2次keepalive探测间隔时间 */  
    inKeepAlive.keepaliveinterval = 5000;   
    /* 开始首次keepalive探测前的tcp空闲时间 */  
    inKeepAlive.keepalivetime     = 5000;   
  
    ret = WSAIoctl((unsigned int)s,  
            SIO_KEEPALIVE_VALS,  
            (LPVOID)&inKeepAlive,   
            ulInLen,  
            (LPVOID)&outKeepAlive,   
            ulOutLen,  
            &ulBytesReturn,   
            NULL,   
            NULL);  
    if (ret == SOCKET_ERROR)  
    {  
        printf ("error: %d\n", WSAGetLastError());  
    }  
}

更多golang知识请关注golang教程栏目。

以上就是golang判断tcp是否断开的方法的详细内容,更多请关注zzsucai.com其它相关文章!

 标签: golang,tcp,
积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!