Boost asio lee un número desconocido de bytes

Tengo 2 casos:

  1. Client connects, send no bytes and wait for server response.
  2. Client connects, send more than 1 bytes and wait for server response.

Problem is next: in 1st case I should read no bytes and get some server response. in 2nd case I should read at least 1 byte and only then I'll get a server response. If i try to read at least 0 bytes, like this:

async_read(sock, boost::asio::buffer(data),
            boost::bind(&server::read, this,

I will never get proper server reposonse in 2nd case.

But if I read at least 1 byte than this async_read operation will never ends.

So, how can I process this cases?

Update 1: I'm still searching for solution without using time limit.

preguntado el 30 de junio de 12 a las 14:06

3 Respuestas

How do you expect this to work? Does the response vary between the first and second case? If it does vary, you cannot do this reliably because there is a race condition and you should fix the protocol. If it does not vary, the server should just send the response.

The solution to this problem is not an asio issue.

Respondido 01 Jul 12, 14:07

Yes, responses are different. - Vladimar

I'm talking about asio for example and for founding solution is asio. - Vladimar

If you cannot change the protocol, the server must have a timeout to decide what response to send. A solution without a time limit is either an immediate response assuming the client sent nothing, or an infinite wait for the client to send something. This is silly, so you must have a timeout. Once you have a timeout, just use the timeout features in asio. - Janm

Aquí esta lo que hice

 while (ec != boost::asio::error::eof) {


        size_t buffersize = socket->read_some(

        if (buffersize > 0) {

            cout << "received" << endl;

            for (unsigned int i=0; i < buffersize; ++i) {

                cout <<;

            cout << "" << endl;



        cout<<"error "<<ec.message()<<endl;

That is a small snippet of my code I hope it helps you can read a set amount of data and append it to a vector of bytes if you like and process it later.

Espero que esto ayude

Respondido 27 Jul 12, 12:07

Thanks for your reply! I can't check it right now, but I'll check it soon. - Vladimar

I guess u need to use the data which the client send to make the proper server response in case 2, and maybe make a default response in case 1. So there is no time limit about how long the client should send the data after connected the server? Maybe u should start a timer waiting for the special limited time after the server accepted the connection. If the server receive the data in time, it's case 2. If time is over, then it's case 1.

Respondido 01 Jul 12, 05:07

Thanks for your answer. Yes, time limit is a kind of reserve solution. I'm still trying to find a solution without any delay. - Vladimar

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.