Home  >  Article  >  Backend Development  >  How to determine whether tcp is disconnected in golang

How to determine whether tcp is disconnected in golang

尚
Original
2019-12-17 10:48:105993browse

How to determine whether tcp is disconnected in golang

Golang's method to determine whether tcp is disconnected:

keepalive detection. For keepalive set up, when tcp detects that the peer socket is no longer available (it cannot Send a detection packet, or the detection packet does not receive an ACK response packet), select will return that the socket is readable, and return -1 during recv, and set errno to ETIMEDOUT. At this time, the status of TCP is disconnected.

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());  
    }  
}

For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of How to determine whether tcp is disconnected in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn