Boost Asio async_read不会停止阅读?

Pol*_*878 1 c++ boost asynchronous boost-asio

所以,

我一直在玩Boost asio函数和套接字(特别是异步读/写).现在,我认为boost::asio::async_read只有当新的缓冲区从网络连接进入时才调用处理程序...但是它不会停止读取相同的缓冲区,因此不断调用处理程序.我已经能够通过检查传输的字节数来缓解它,但它基本上处于一个浪费CPU循环的忙等待循环中.

这是我有的:

class tcp_connection : : public boost::enable_shared_from_this<tcp_connection> 
{
public:
    // other functions here

    void start()
    {
    boost::asio::async_read(socket_, boost::asio::buffer(buf, TERRAINPACKETSIZE),
        boost::bind(&tcp_connection::handle_read, shared_from_this(),
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
    }

private:
    const unsigned int TERRAINPACKETSIZE = 128;
    char buf[TERRAINPACKETSIZE];


    void handle_read(const boost::system::error_code& error, size_t bytesT)
    {
        if (bytesT > 0)
        { 
             // Do the packet handling stuff here
        }

        boost::asio::async_read(socket_, boost::asio::buffer(buf, TERRAINPACKETSIZE),
        boost::bind(&tcp_connection::handle_read, shared_from_this(),
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
    }
};
Run Code Online (Sandbox Code Playgroud)

有些东西被删除,但基本上会创建一个新的连接然后start()被调用.有什么我缺少的东西,以便该handle_read方法不会被连续调用?

Éri*_*ant 6

猜猜:你检查errorhandle_read?如果套接字是由于某种原因,错误状态,我想这对嵌套调用async_read制成handle_read会立即"完成",造成的直接通话handle_read