Why boost::asio::async_read completion sometimes executed with bytes_transferred=0 and ec=0?

偶尔善良 提交于 2020-01-23 09:26:06

问题


Recently I have found an annoying problem with boost:asio::async_read. When I transfer large amounts of data, say a file of about 9GB, boost:asio::async_read works well in most of the time, but sometimes the completion of async_read is executed with bytes_transferred=0 and ec=0! And sometimes the completion of async_read is executed with bytes_transferred!=sp_recv_data->size() and ec still equal to 0. My code just like below:

void CNetProactorClientImpl::async_recv()
{
    auto sp_vec_buf = make_shared<std::vector<unsigned char>>(1 * 1024 * 1024);

    /*
    boost::asio::async_read
    this function is used to asynchronously read a certain number of bytes of data from a stream.
    the function call always returns immediately. the asynchronous operation will continue until one of the following conditions is true:
        *the supplied buffers are full. that is, the bytes transferred is equal to the sum of the buffer sizes.
        *an error occurred.
    */
    boost::asio::async_read(*sp_socket,
        boost::asio::buffer(sp_vec_buf),
        bind(&CNetProactorClientImpl::async_recv_complete_handler, this,
            sp_vec_buf,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
}
void CNetProactorClientImpl::async_recv_complete_handler(shared_ptr<std::vector<unsigned char>> sp_recv_data, const boost::system::error_code& ec, size_t bytes_transferred)
{
    if (!ec)
    {
        //no error
        if (bytes_transferred == 0)
        {
            //Sometimes it trigger here, ec is 0 but also bytes_transferred! Why???
            assert(bytes_transferred == sp_recv_data->size());
        }
        if (bytes_transferred != sp_recv_data->size())
        {
            /*
            Sometimes it trigger here, it is also a strange behavior that bytes_transferred NOT equal to sp_recv_data->size() because the Boost document say:
            The asynchronous operation will continue until one of the following conditions is true:
                *The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
                *An error occurred.
            */
            assert(bytes_transferred == sp_recv_data->size());
        }
        //do normal action
    }
    else
    {
        //error handling
        disconnect();
    }
}

My boost version is 1.61. Testing environment: win10 pro +VS2015 Update3.

来源:https://stackoverflow.com/questions/38419969/why-boostasioasync-read-completion-sometimes-executed-with-bytes-transferred

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