我正在使用客户端写入服务器。我想检查套接字是否已打开以便在客户端中写入数据,并且在建立连接后10秒钟未准备就绪时,我想打印一条错误消息并由于超时而退出客户端。

客户端仅通过发送功能即可正常工作,并且我能够将文件从客户端传输到服务器。但是,当我实现select()功能时,客户端现在将在sel_value设置为0的情况下超时。

为了使阅读更容易,我删除了具有发送功能的代码,因为还有一些将逻辑读入缓冲区的逻辑。

//set up select for sending
fd_set wfds;
struct timeval timeout;
while (1) {
    FD_ZERO(&wfds);
    FD_SET(sockfd, &wfds);

    timeout.tv_sec = 10;
    timeout.tv_usec = 0; //no us

    int sel_value = select(sockfd+1, &wfds, NULL, NULL, &timeout);
    cout<<"sel_value is: "<<sel_value<<endl;
    if(sel_value == -1){
        perror("select");

    }else if(sel_value == 0){
        printf("Timeout. Cannot send for 10s \n");
        break;
    }
    else{
        if(FD_ISSET(sockfd, &wfds)){
            //my code never reaches this point, but here is where we send
            //code to send stuff
        }
    }

}

最佳答案

您正在从头到尾进行此操作。您应该只执行发送,并且仅在发送引起EAGAIN/EWOULDBLOCK时才选择可写性。套接字几乎总是准备好写入,除非套接字发送缓冲区已满。您将系统调用加倍并增加延迟的方式。

关于c++ - 在使用send()之前,先使用select()检查套接字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43552960/

10-11 21:57
查看更多