Boost asio read an unknown number of bytes

别说谁变了你拦得住时间么 提交于 2020-01-02 21:23:37

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/11274577/boost-asio-read-an-unknown-number-of-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!