go语言如何判断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()); } }
看完这篇文章,你们学会go语言判断tcp是否断开的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读。