简体   繁体   中英

Sockets in C, Non-blocking send() and recv() with select() method

I want to make a non-blocking send() and recv() with select() and FD_ISSET(). I run into this behavior in which FD_ISSET() will be true for the first socket, and all other sockets are always not ready. I am confused why that is happening and I am wondering if I am using select() properly.

If I sent 100 requests, eventually one of the socket other than the first will be ready to recv(), but I am not getting that behavior.

  for(int i = 0; i < P - 1; i++) {
    sockArr[i] = GetSocket(server, port);
    if (sockArr[i] < 0) {
      // handle error
    }
    fcntl(sockArr[i], F_SETFL, O_NONBLOCK);
    if(sockArr[i] > maxfd) {
      maxfd = sockArr[i];
    }
  }

  fd_set sockSet;
  for(int i = 0; i < P - 1; i++) {
    numBytes = send(sockArr[i], request, requestLen, 0);
    if (numBytes < 0 || numBytes != requestLen) {
      // handle error
    }

    // read from other stackoverflow post you need to rest
    // per select() call
    FD_ZERO(&sockSet);
    for(int i = 0; i < P - 1; i++) {
      FD_SET(sockArr[i], &sockSet);
    }

    if(select(maxfd+1, &sockSet, NULL, NULL, NULL)) {
      for(int j = 0; j < i; j++) {
        if(FD_ISSET(sockArr[j], &sockSet)) { // <------ only true for j = 0
         numBytes = recv(sockArr[j], buffer, MAXBUFLEN - 1, 0);
          if (numBytes < 0) {
            // handle error
          }
        }
      }
    }
  }

Your first for loop needs to terminate after the send() calls, and you should then start another to handle the selects and receives.

You need to check for recv() returning zero as well as -1, and close the socket and remove it from the FD set in either case.

You also need to loop while j <= P .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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