选择 TCP 套接字超时

问题描述 投票:0回答:1

我对这段代码有疑问:

FD_ZERO(&cset);
FD_SET(s, &cset);

tval.tv_sec = TIMEOUT; 
tval.tv_usec = 0; 

n = select(FD_SETSIZE, &cset, NULL, NULL, &tval);

if (n==-1) {
    printf(" select() failed \n");
    exit(-1);
}
if (n>0) {
    check_control = connect(s,(struct sockaddr*)
    &indirizzo_remoto,sizeof(indirizzo_remoto));

    if (check_control == -1) {
        printf("Errore connect()\n");
    }

}else{
    printf("Timeout. I'll shutdown the client");
    exit(-1);
}

我想为连接插入超时,但它不起作用:

我使用了正确的服务器 IP 地址和端口号,但连接超时。

非常感谢您的帮助。

sockets timeout select-function
1个回答
4
投票

在同一套接字上调用

select()
之前,您正在使用 connect() 检查给定套接字是否处于
可读
状态。那永远不会起作用。未连接的 TCP 套接字永远不会处于可读状态,并且不能与
select()
一起使用,直到首先对其调用
connect()

实现

connect()
调用超时的唯一方法是首先将套接字置于非阻塞模式(默认情况下套接字是阻塞的),然后调用
connect()
(如果套接字处于阻塞状态,则返回
EINPROGRESS
错误)尝试连接),然后使用
select()
等待套接字进入 writable 状态,表示连接成功,或者进入 error 状态,表示连接失败。

试试这个:

fcntl(s, F_SETFL, O_NONBLOCK);

或者:

flags = 1;
ioctl(s, FIOBIO, &flags);

取决于您的平台。

然后:

check_control = connect(s, (struct sockaddr*) &indirizzo_remoto, sizeof(indirizzo_remoto));
if (check_control == -1)
{
    if (errno != EINPROGRESS)
    {
        printf("Errore connect()\n");
        exit(-1);
    }

    FD_ZERO(&wset);
    FD_SET(s, &wset);

    FD_ZERO(&eset);
    FD_SET(s, &eset);

    tval.tv_sec = TIMEOUT; 
    tval.tv_usec = 0; 

    n = select(s+1, NULL, &wset, &eset, &tval);
    if (n == -1)
    {
        printf(" select() failed \n");
        exit(-1);
    }

    if (n == 0)
    {
        printf("Timeout. I'll shutdown the client");
        exit(-1);
    }

    if (FD_ISSET(s, &eset))
    {
        printf("Cannot connect. I'll shutdown the client");
        exit(-1);
    }

    int err = -1;
    getsockopt(s, SOL_SOCKET, SO_ERROR, &err, sizeof(err));
    if (err != 0)
    {
        printf("Cannot connect. I'll shutdown the client");
        exit(-1);
    }
}

// connected...
© www.soinside.com 2019 - 2024. All rights reserved.