How to find out if data is readable from a socket in boost :: asio?

I am using the Boost ASIO library to record the TCP client program.

The protocol starts with a banner line when you connect, and then '\ r \ n' I can send commands at any time, like smtp.

However, the server can also send me data when I do not ask for it, and it ends with '\ r \ n'

I have a line like this to read and parse the initial connecting banner. This means stop reading when I get "\ r \ n".

boost::asio::streambuf response_;
...
boost::asio::async_read_until(socket_, response_, "\r\n",
            boost::bind(&PumpServerClient::HandleReadBanner, this,
                boost::asio::placeholders::error));

But at different times I want to ask a question, is there data? if there is, read it before "\ r \ n". I feel like I need a peeping function, but I don’t see what it is.

, , async_read_until. ... . . , , .

void client::HandleReadRequest(const boost::system::error_code& err)
{
    if (!err){
        // Got some data, print it out
        std::ostringstream ss;
        ss << &response_;

        std::cout << ss.str() << std::endl;

         // Keep reading...
        boost::asio::async_read_until(socket_, response_, "\r\n",
          boost::bind(&client::HandleReadRequest, this, boost::asio::placeholders::error));

        std::cout << "keep reading" << std::endl;
    }
    else
    {
        std::cout << "Error: " << err.message() << "\n";
    }
}

, , . , .

:

:: ASIO:: async_read_until (socket_, response_, "\ r\n" ,               :: Bind (& :: HandleReadRequest, , :: ASIO:: :: )); , , a\r\n response_, HandleReadRequest. async_read_until. , ... ... , , .

+3
2

, socket_base::bytes_readable, :

boost::asio::ip::tcp::socket socket(io_service); 
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
+3

async- asio "". , asio , , . , .

, , , , asio , , " " , . , async_read.

async_read_until , , .

+2

Source: https://habr.com/ru/post/1725772/


All Articles