【发布时间】:2017-04-21 22:32:16
【问题描述】:
我正在使用我的客户端写入服务器。我想检查套接字是否已打开以在我的客户端中写入,如果在建立连接后 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
}
}
}
【问题讨论】:
-
首选poll(2) 而不是旧的
select。阅读C10k problem