Boost asio read an unknown number of bytes

2019-05-31 09:25发布

I have 2 cases:

  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::asio::transfer_at_least(0),
            boost::bind(&server::read, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));

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.

3条回答
Lonely孤独者°
2楼-- · 2019-05-31 09:51

here is what I did

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

        vector<char>socketBuffer(messageSize);

        size_t buffersize = socket->read_some(
                                    boost::asio::buffer(socketBuffer),ec);

        if (buffersize > 0) {

            cout << "received" << endl;

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

                cout << socketBuffer.at(i);
            }

            cout << "" << endl;
        }

        socketBuffer.clear();

    }

    if(!ec){
        cout<<"error "<<ec.message()<<endl;
    }
    socket->close();

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.

Hope this helps

查看更多
Evening l夕情丶
3楼-- · 2019-05-31 10:04

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.

查看更多
趁早两清
4楼-- · 2019-05-31 10:11

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.

查看更多
登录 后发表回答