src/nb_socket_io.cpp
// Two timeouts.  One per read.  Another for the total time allowed to read all bytes.
Two timeouts.  One per read.  Another for the total time allowed to read all bytes.
Two timeouts . One per read . Another for the total time allowed to read all bytes .
bool NBSocketIO::ReadNBytes(int n, char *bytes) const {
  fd_set fds;
  FD_ZERO(&fds);
  FD_SET(fd_, &fds);
  struct timeval timeout;
  time_t start_t = time(NULL);
  int num_remaining = n;
  char *bytes_ptr = bytes;
  while (num_remaining > 0) {
    timeout.tv_sec  = kReadTimeoutSecs;
    timeout.tv_usec = kReadTimeoutUSecs;
    int ret = select(fd_ + 1, &fds, NULL, NULL, &timeout);
    if (ret != 0 && ret != 1) {
      return false;
    } else if (ret == 0) {
      time_t now = time(NULL);
      double elapsed_secs = difftime(now, start_t);
      if (elapsed_secs > kReadTotalTimeoutSecs) return false;
    } else {
      if (! FD_ISSET(fd_, &fds)) {
	return false;
      }
      int read_sz = read(fd_, bytes_ptr, num_remaining);
      if (read_sz <= 0) {
	return false;
      }
      if (read_sz > num_remaining) {
	return false;
      }
      bytes_ptr += read_sz;
      num_remaining -= read_sz;
    }
  }
  return true;
}
bool NBSocketIO :: ReadNBytes ( int n , char * bytes ) const { fd_set fds ; FD_ZERO ( & fds ) ; FD_SET ( fd_ , & fds ) ; struct timeval timeout ; time_t start_t = time ( NULL ) ; int num_remaining = n ; char * bytes_ptr = bytes ; while ( num_remaining > 0 ) { timeout . tv_sec = kReadTimeoutSecs ; timeout . tv_usec = kReadTimeoutUSecs ; int ret = select ( fd_ + 1 , & fds , NULL , NULL , & timeout ) ; if ( ret != 0 && ret != 1 ) { return false ; } else if ( ret == 0 ) { time_t now = time ( NULL ) ; double elapsed_secs = difftime ( now , start_t ) ; if ( elapsed_secs > kReadTotalTimeoutSecs ) return false ; } else { if ( ! FD_ISSET ( fd_ , & fds ) ) { return false ; } int read_sz = read ( fd_ , bytes_ptr , num_remaining ) ; if ( read_sz <= 0 ) { return false ; } if ( read_sz > num_remaining ) { return false ; } bytes_ptr += read_sz ; num_remaining -= read_sz ; } } return true ; }
Two timeouts.
Two timeouts .
// Typically -1 indicating an error // Timeout.  Should I check for EAGAIN or EWOULDBLOCK or some such? // Not sure how this could happen // Now we can make a blocking read // Really shouldn't happen!