C connect实现Timeout效果(Windows)

Posted 离水的鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C connect实现Timeout效果(Windows)相关的知识,希望对你有一定的参考价值。

int SocketClient::connectTimeOutForWin(SOCKET &connect_fd, const int &timeout, const sockaddr_in &server)
{
    int error=-1, len;
    len = sizeof(int);
    timeval tm;
    fd_set set;
    unsigned long ul = 1;

     //设置为非阻塞模式

    ioctlsocket(connect_fd,FIONBIO,&ul);

    bool ret = false;
    if( connect(connect_fd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)
    {
        tm.tv_sec = timeout;
        tm.tv_usec = 0;
        FD_ZERO(&set);
        FD_SET(connect_fd, &set);
        if( select(-1, NULL, &set, NULL, &tm) > 0)
        {

              getsockopt(connect_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);

            if(error == 0) ret = true;
            else ret = false;
        } else ret = false;
    }
    else ret = true;
    ul = 0;


//设置为阻塞模式
    ioctlsocket(connect_fd,FIONBIO,&ul);

    if(!ret){
        closesocket(connect_fd);
//        fprintf(stderr,"Connect server fail in WIN\n");
    }
    return ret;
}

 

以上是关于C connect实现Timeout效果(Windows)的主要内容,如果未能解决你的问题,请参考以下文章

Genymotion Unable to create Virtual Device:Connection timeout

ORA-12170: TNS:Connect timeout occurred

为什么workbench3.3 每次启动都显示 faild to connect to the wind river registry on host “localhost“

HttpClient连接池抛出大量ConnectionPoolTimeoutException: Timeout waiting for connection异常排查

Genymotion--Unable to create Genymotion virtual devices:Connection timeout

INBOUND_CONNECT_TIMEOUT与SQLNET.INBOUND_CONNECT_TIMEOUT小结