为什么boost :: asio :: async_read完成有时用bytes_transferred = 0和ec = 0执行?

时间:2016-07-17 09:50:41

标签: c++ boost boost-asio

最近我发现了boost:asio::async_read的烦人问题。 当我传输大量数据(例如大约9GB的文件)时,async_read在大多数情况下运行良好,但有时bytes_transferred=0的完成会使用ec=0!和{{1}执行有时async_read的完成是用bytes_transferred!=sp_recv_data->size()执行的,而ec仍然等于0。 我的代码如下:

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();
    }
}

我的提升版是1.61。测试环境:win10 pro + VS2015 Update3。

0 个答案:

没有答案