src/socket_io.cpp
// Expects a 10 byte length value prior to the string.
Expects a 10 byte length value prior to the string.
Expects a 10 byte length value prior to the string .
bool SocketIO::ReadMessage(string *str, int timeout_secs) const {
  *str = "";
  if (! WaitForReadable(timeout_secs)) {
    return false;
  }
  char len_str[11];
  ssize_t ret = read(fd_, len_str, 10);
  if  (ret != 10) {
    return false;
  }
  len_str[10] = 0;
  int len;
  if (sscanf(len_str, "%10d", &len) != 1) {
    Warning("Couldn't parse len_str: \"%s\"\n", len_str);
    return false;
  }
  if (len < 0 || len > kMaxMessageLen) {
    Warning("SocketIO::ReadMessage() bad length %s\n", len_str);
    return false;
  }
  unique_ptr<char []> buf( new char[len + 1]);
  if (len == 0) {
    buf[0] = 0;
    return true;
  }
  int cum = 0;
  while (true) {
    int left = len - cum;
    ssize_t ret = read(fd_, buf.get(), left);
    if (ret <= 0) {
      Warning("SocketIO::ReadString: failed to read; ret %i; len %i cum %i left %i\n", (int)ret, len, cum, left);
      if (cum > 0) {
	buf[cum] = 0;
	Warning("  Read so far: %s\n", str->c_str());
      }
      return false;
    }
    buf[ret] = 0;
    *str += buf.get();
    cum += ret;
    if (cum >= len) break;
  }
  return true;
}
bool SocketIO :: ReadMessage ( string * str , int timeout_secs ) const { * str = " " ; if ( ! WaitForReadable ( timeout_secs ) ) { return false ; } char len_str [ 11 ] ; ssize_t ret = read ( fd_ , len_str , 10 ) ; if ( ret != 10 ) { return false ; } len_str [ 10 ] = 0 ; int len ; if ( sscanf ( len_str , " " , & len ) != 1 ) { Warning ( " \" \" \n " , len_str ) ; return false ; } if ( len < 0 || len > kMaxMessageLen ) { Warning ( " \n " , len_str ) ; return false ; } unique_ptr < char [ ] > buf ( new char [ len + 1 ] ) ; if ( len == 0 ) { buf [ 0 ] = 0 ; return true ; } int cum = 0 ; while ( true ) { int left = len - cum ; ssize_t ret = read ( fd_ , buf . get ( ) , left ) ; if ( ret <= 0 ) { Warning ( " \n " , ( int ) ret , len , cum , left ) ; if ( cum > 0 ) { buf [ cum ] = 0 ; Warning ( " \n " , str -> c_str ( ) ) ; } return false ; } buf [ ret ] = 0 ; * str += buf . get ( ) ; cum += ret ; if ( cum >= len ) break ; } return true ; }
Expects a 10 byte length value prior to the string.
Expects a 10 byte length value prior to the string .
// We don't want to spit out warning messages every time someone connects and then // doesn't send data in the format we expect.  Monitoring services will do that, // people will telnet, etc. // Warning("Couldn't read string length str from socket\n"); // Do we allow the writing of empty strings?