首頁 > 後端開發 > Golang > 主體

golang判斷tcp是否斷開的方法

發布: 2019-12-17 10:48:10
原創
5999 人瀏覽過

golang判斷tcp是否斷開的方法

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中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板