Linux 如何接受超时的套接字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14045064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:07:34  来源:igfitidea点击:

How to accept socket with timeout

clinuxwindows

提问by Boris

Is there is a timeout crossplatform soulution to accept client using acceptfunction without setting socket to non-blocking?

是否有超时跨平台解决方案来接受客户端使用accept函数而不将套接字设置为非阻塞?

I know that i should use selectfunction to it, but what i'm doing wrong?

我知道我应该select对它使用函数,但是我做错了什么?

SOCKET NativesAcceptClient(SOCKET s, int timeout)
{
   int iResult;
   struct timeval tv;
   fd_set rfds;
   FD_ZERO(&rfds);
   FD_SET(s, &rfds);

   tv.tv_sec = (long)timeout;
   tv.tv_usec = 0;

   iResult = select(s, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
   if(iResult > 0)
   {
      return accept(s, NULL, NULL);
   }
   else
   {
     //always here, even if i connect from another application
   }
   return 0;
}

How to fix that? Thanks!

如何解决?谢谢!

回答by ryanbwork

The first parameter of the selectcall should be equal to the the highest number file descriptor in your fd_set set plus 1 (see here). Try changing the first argument to s+1; you will need to add some logic when your have more than one socket in your set.

select调用的第一个参数应该等于 fd_set 集合中最大编号的文件描述符加 1(参见此处)。尝试将第一个参数更改为s+1; 当您的集合中有多个套接字时,您将需要添加一些逻辑。

回答by arayq2

The first argument of select() is an int that is at least 1 greaterthan the highest value of the file descriptors in any of the bitsets. In this case

的选择的第一个参数()是一个int是至少1更大的比文件描述符中的任何位集的最高值。在这种情况下

iResult = select(s + 1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);

should work.

应该管用。

回答by Remy Lebeau

select()returns >0 if a socket is signaled, 0 on timeout, and -1 on error. What value is select()actually returning to you? You are only checking for >0 and <=0, which means you are not differentiating between -1 and 0. If it is returning 0 then no client is connecting to your socket, but if it is returning -1 then your socket is likely not valid to begin with.

select()如果套接字有信号,则返回 >0,超时时返回 0,错误时返回 -1。什么价值select()实际上回报给你?您只检查 >0 和 <=0,这意味着您没有区分 -1 和 0。如果它返回 0,则没有客户端连接到您的套接字,但如果它返回 -1,则您的套接字很可能开始无效。