代码之家  ›  专栏  ›  技术社区  ›  Brian

调整套接字连接调用超时

  •  2
  • Brian  · 技术社区  · 17 年前

    在Win32环境中,有没有办法“调优”套接字上的超时 connect()

    3 回复  |  直到 17 年前
        1
  •  2
  •   fhe    17 年前

    是的,这是可能的。

    如果在之后处于非阻塞模式 connect() select() 等待I/O就绪。此函数有一个用于指定超时值的参数,如果超时,将返回0。

        2
  •  0
  •   kuchi    14 年前

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;
    
    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");
    
    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");
    

    您也可以尝试alarm()。样本:

    signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */
    alarm( secs ); /* secs is your timeout in seconds */
    if ( connect( fd, addr, addrlen ) < 0 )
    {
        if ( errno == EINTR ) /* timeout, do something below */
            ...
    }
    alarm( 0 ); /* cancel the alarm */
    
        3
  •  0
  •   user207421    12 年前

    不,这是不可能的。默认连接超时可以减少,但不能增加。