1

Currently I am receiving data synchronously in the following manner

             boost::array<char, 2000> buf;
             while(true)
            {
                std::string dt;
                size_t len = connect_sock->receive(boost::asio::buffer(buf, 3000));
                std::copy(buf.begin(), buf.begin()+len, std::back_inserter(dt));
                std::cout << dt;
            }

My question is whether this method is efficient enough to receive data that exceed the buffer size . Is there any way that I could know exactly how much data is available so that I could adjust the buffer size accordingly ? (The reason for this is that my server sends a particular response to a request that needs to be processed only when an entire response has been stored in a string variable.

MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 2
    did you try it? TCP is connection oriented so unless you make the length part of the protocol (eg: send the length as the first byte) you will not know how much data is going to be sent. You can of course keep reading till the connection is closed (probably when len < length of your buffer but check the documentation for that) or until you encounter some protocol specific end of packet marker. – msam Mar 28 '13 at 09:14
  • 1
    [This](http://stackoverflow.com/a/15069733/1053968) answer provides a few options: resizing manually, auto-resizing, and transmitting size as part of the protocol. – Tanner Sansbury Mar 28 '13 at 13:27
  • You've [asked a similar question](http://stackoverflow.com/q/15558223/283302) previously – Sam Miller Mar 28 '13 at 16:44

1 Answers1

2

If you are sending data using TCP, you have to take care of this at the application protocol level.

For example, you could prefix each request with a header that would include the number of bytes that make up the request. The receiver, having read and parsed the header, would know how many more bytes it would need to read to get the rest of the request. Then it could repeatedly call receive() until it gets the correct amount of data.

NPE
  • 486,780
  • 108
  • 951
  • 1,012