0

I am using a socket library (I'd rather not not use it) whose recv operations works with std::string, but is just a wrapper for one call of the recv socket function, so it is probably that I only got some part of the message I wanted. My first instinct was to go in a loop and append the received string to another string until I get everything, but this seems inefficient. Another possibility was to do the same with a char array, but this seems messy. (I'd have to check the strings size before adding into the array and if it overflowed I need to store the string somewhere until the array is empty again.. )

So I was thinking about using a stringstream. I use a TLV protocol, so I need to first extract two bytes into an unsigned short, then get a certain amount of bytes from the stringstream and then loop again until I reach a delimiter field.

Is there any better way to do this? Am I completely on the wrong track? Are there any best practices? So far I've always only seen direct use of the socket library with char arrays so I'm curious why using `std::string`` with stringstreams could be a bad idea..

Edit: Replying to the comment below: The library is one we use internally, its not public (its nothing special though, mostly just a wrapper around the socket library to add exceptions, etc.).

I should mention that I have a working prototype using the socket library directly.

This works something like:

int lengthFieldSize = sizeof(unsigned short);
int endOfBuffer= 0;//Pointer to last valid position in buffer.                                     
while(true) {
  char buffer[RCVBUFSIZE];
  while(true) {
    int offset= endOfBuffer;
    int rs= 0;
    rs= recv(sock, buffer+offset, sizeof(buffer)-offset, 0);
    endOfBuffer+= rs;
    if(rs < 1) {
      // Received nothing or error.                                                                         
      break;
    } else if(endOfBuffer == RCVBUFSIZE) {
      // Buffer full.                                                                               
      break;
    } else if(rs > 0 && endOfBuffer > 1) {
      unsigned short msglength= 0;
      memcpy((char *) &msglength, buffer+endOfBuffer-lengthFieldSize, lengthFieldSize);
      if(msglength == 0) {
        break; // Received a full transmission.                                                    
      }
    }
  }
  unsigned int startOfData = 0;
  unsigned short protosize= 0;
  while(true) {
    // Copy first two bytes into protosize (length field)                                          
    memcpy((char *) &protosize, buffer+startOfData, lengthFieldSize);
    // Is the last length field the delimiter?                                                     
    // Then reply and return. (We're done.)                                                        
    // Otherwise: Is the next message not completely in the buffer?                            
    // Then break. (Outer while will take us back to receiving)                                    
    if(protosize == 0) {
      // Done receiving. Now send:                                                                 
      SendReplyMsg(sock, lengthFieldSize);
      // Clean up.                                                                                 
      close(sock);
      return;
    } else if((endOfBuffer-lengthFieldSize-startOfData) < protosize) {
      memmove(buffer, buffer+startOfData, RCVBUFSIZE-startOfData);
      //Adjust endOfBuffer:                                                                        
      endOfBuffer-=startOfData;
      break;
    }
    startOfData+= lengthFieldSize;
    gtControl::gtMsg gtMessage;
    if(!gtMessage.ParseFromArray(buffer+startOfData, protosize)) {
      cerr << "Failed to parse gtMessage." << endl;
      close(sock);
      return;
    }
    // Move position pointer forward by one message (length+pbuf)                                  
    startOfData+= protosize;
    PrintGtMessage(&gtMessage);
  }
}

So basically I have a big loop which contains a receiving loop and a parsing loop. There's a character array being passed back and forth as I can't be sure to have received everything until I actually parse it. I'm trying to replicate this behaviour using "proper" C++ (i.e. std::string)

1
  • (If I took your explamation right.) I'm pretty sure that string::append is no less efficient then operator<<(ostringstream&, const char*). It would be helpfull if you gave some code samples illustrating your ideas and probably name the library under consideration. Nov 30, 2011 at 18:00

1 Answer 1

2

My first instinct was to go in a loop and append the received string to another string until I get everything, but this seems inefficient.

String concatenation is technically platform dependent, but probably str1 + str2 will require one dynamic allocation and two copies (from str1 and str2). That's sorta slow, but it's far faster than network access! So my first piece of advice would be to go with your first instinct, to find out whether it's both correct and fast enough.

If it's not fast enough, and your profiler shows that the redundant string copies are to blame, consider maintaining a list of strings (std::vector<string*>, perhaps) and joining all the strings together once at the end. This requires some care, but should avoid a bunch of redundant string copying.

But definitely profile first!

1
  • Thanks, this is helpful. I am expecting messages to be possibly on the order of MB and had tried something similar on a python client already. Concatenating strings there was a big bottleneck, so I'll probably go with the list of strings first right away.
    – dinyar
    Nov 30, 2011 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.