简体   繁体   English

使用非阻塞套接字时,recv()返回什么?

[英]What does recv() return when using non-blocking sockets?

If I set a socket to non-blocking, what should I get from recv() if there is no new data to be read? 如果将套接字设置为非阻塞,如果没有要读取的新数据,我应该从recv()得到什么?

At the moment, I am using and if statement to see if I received anything greater than -1. 目前,我正在使用if语句查看是否收到大于-1的值。 But it seems to block somehow if nothing is received. 但是,如果什么也没收到,它似乎会以某种方式阻止。 This is what my code looks like: 这是我的代码如下所示:

flags = fcntl(newfd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(newfd, F_SETFL, flags);

while(1){
...
... 
if( (recvBytes = recv(newfd, recvBuf, MAXBUFLEN-1, 0)) > -1) {
 ...
     }

}

According to my manpage: 根据我的手册:

If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, recv() shall block until a message arrives. 如果套接字上没有可用的消息,并且套接字的文件描述符中未设置O_NONBLOCK,则recv()将阻塞直到消息到达。 If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, recv() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK]. 如果套接字上没有可用的消息,并且套接字的文件描述符上设置了O_NONBLOCK,则recv()将失败,并将errno设置为[EAGAIN]或[EWOULDBLOCK]。

I would suggest the following superficial change. 我建议进行以下肤浅的改变。 It doesn't change the logic of your code but it does make it very clear what is being tested, when and what for. 它不会改变代码的逻辑,但确实可以清楚地说明正在测试的内容,时间和用途。

int response;
...
while(1){
  ...
  response = recv(newfd, recvBuf, MAXBUFLEN-1, 0);
  if (response <= 0)
  {  // assuming that a zero or negative response indicates
     // test errno for EAGAIN or EWOULDBLOCK per JB comment
   ...
  } else {
    // response contains number of bytes received..
  }

 ...
} // end while

A good compile will optimize the assignment and if statement into something like you originally wrote. 良好的编译将优化分配和if语句,使其类似于您最初编写的内容。 So this style of coding is to make it easy to think about what the code does. 因此,这种编码方式使思考代码的工作变得容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM