您好,登錄后才能下訂單哦!
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是否斷開的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。