5

I would like to know if it is possible to, for instance, take a piece of data in memory, read it into an output stringstream (as binary data) and write this onto a socket for a client application to process.

The problem I run into while attempting this is the following:

Example:

char name[1024] = "Test";
std::ostringstream message (std::stringstream::out | std::stringstream::binary);

len = strlen(name);
message.write(reinterpret_cast<const char*>(&len), sizeof(int));
message.write(test, len*sizeof(char));

I want to write this stringstream to the socket with all of the data in it, but the problem is this: The stringstream write only executes the first time, in this case writing 4 (the length of the string) and none of the subsequent writes. Am I missing something here?

If this is not the best way to do it, what would be the best way to accomplish this? This is partly to reduce file I/O for cached memory snapshots.

Thanks in advance..

Jan Swart
  • 6,761
  • 10
  • 36
  • 45
  • Please include a complete test case. For all we can tell, the `ostringstream` has buffered all the data, but your method of interpreting the buffer contents got stuck at the first NUL byte. – Potatoswatter Apr 07 '14 at 07:41

1 Answers1

4

Your code (with minor fixes) appears to work for me, so you might check to be sure that you are correctly handling the buffered binary data, i.e. you do not assume that the std::string contains a string.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • @Potatoswatter..thanks for the reply and sorry for the delay in my reply. Yes, the problem was that one of the writers on the client side stopped at a null terminator in the string, that was part of the binary data. I appreciate your help. – Jan Swart Apr 08 '14 at 12:58