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是否斷開的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!