为什么boost :: asio :: async_read无法读取请求的字节数?

时间:2016-02-26 17:37:38

标签: c++ boost boost-asio

我遇到了boost::asio::async_read在第二次通话中失败的问题,这是一种奇怪的方式:

std::atomic<error_code> ec(asio::error::would_block);
size_t len = 0;

// 1st call
asio::async_read(socket,
                 asio::buffer(buffer+X),
                 asio::transfer_exactly(512-X),
                 [&] (error_code const& err, size_t bytesTransferred)
                 {
                     len = bytesTransferred;
                     ec.store(err, std::memory_order_release);
                 }
);
/////// ... wait for read to complete ...
// 2nd call
asio::async_read(socket,
                 asio::buffer(buffer),
                 asio::transfer_exactly(512),
                 [&] (error_code const& err, size_t bytesTransferred)
                 {
                     len = bytesTransferred;
                     ec.store(err, std::memory_order_release);
                 }
);

常量X是因为我已经有了一些我以其他方式获得的数据, 所以第一次阅读较小。假设X = 364,那么第一次bytesTransferred将是148。然而,我的问题是第二次读取再次返回148个字节,即使 读取完全是512个字节。

我很困惑。第二个调用没有错误条件(我检查err)。 bytesTransferredaync_read传递给我的参数,它是148字节两次。第一次,它与堆栈上的asio::transfer_exactly(148)匹配。第二次,callstack显然有asio::transfer_exactly(512)。这里发生了什么?

特别是第二次调用,第三次调用再次读取512个字节,但也获得512个字节。

[MCVE]

#include <iostream>
#include <atomic>

#include <boost/asio/buffer.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/read.hpp>

// Minimal example, code that works has error checking removed. Class members turned itno globals etc.
namespace {
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::resolver resolver(io_service);
    boost::asio::ip::tcp::socket sock(io_service);
    std::vector<char> data(512);
    boost::asio::mutable_buffers_1 buffer(&data[0], data.size());
    unsigned read_counter = 1;
    std::atomic<unsigned> read_timeout;
}

boost::system::error_code openSocket(const std::string &server,
                                     const std::string &port)
{
    boost::system::error_code error = boost::asio::error::host_not_found;
    using boost::asio::ip::tcp;
    tcp::resolver::query query(server, port);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    while (error && endpoint_iterator != end)
    {
        sock.close();
        sock.connect(*endpoint_iterator++, error);
    }
    if (error)
    {
        std::cerr << "No route\n";
        sock.close(); // Would be wrong to leave it open.
    }
    return error;
}

int read(size_t bytesNeeded)
{
    size_t buffer_len = boost::asio::buffer_size(buffer);
    size_t byteShift = buffer_len - bytesNeeded; // Read into back of buffer.

    const int timeoutSeconds = 10;
    boost::asio::deadline_timer deadline(io_service);
    deadline.expires_from_now(boost::posix_time::seconds(timeoutSeconds)); // This will reset any outstanding timer
    read_counter += 2; // If we'd use +1, after 4 billion cycles it would reset to 0
    read_timeout.store(0, std::memory_order_release); // 0 = no timeout.
    unsigned read_counter_copy = read_counter; // Can't capture global.
    deadline.async_wait([read_counter_copy](boost::system::error_code const&) {
        // read_timeout is very intentionally captured by value - timeout events are numbered
        read_timeout.store(read_counter_copy, std::memory_order_release); }
    );

    // Start reading "asynchronously", wait for completion or timeout:
    std::atomic<boost::system::error_code> ec(boost::asio::error::would_block);
    size_t len = 0;

    boost::asio::async_read(sock, boost::asio::buffer(buffer + byteShift), boost::asio::transfer_exactly(bytesNeeded),
        [&, bytesNeeded](boost::system::error_code const& err, size_t bytesTransferred)
        {
            if (bytesTransferred != bytesNeeded) {
                std::cout << bytesTransferred << " , " << err.message() << std::endl;
            }
            len = bytesTransferred;
            ec.store(err, std::memory_order_release);
        }
    );

    do {
        io_service.run_one();
    } while (read_timeout.load(std::memory_order_acquire) != read_counter && // Continue if the **last** read didn't time out
        (ec.load(std::memory_order_acquire) == boost::asio::error::would_block) && // ec.store() not called,
        !io_service.stopped()); // and program still running.

    deadline.cancel(); // This will set read_timeout, if it wasn't set yet. But we ignore it from now on.

    if (ec.load(std::memory_order_acquire))
    {
        std::cerr << "oops\n"; // Real error handling omitted.
        throw std::runtime_error("");
    }
    else if (read_timeout == read_counter)
    {
        std::cerr << "timeout\n";
    }
    else if (len != bytesNeeded)
    {
        // This is the real problem.
        std::cerr << "Asked " << bytesNeeded << " got " << len;
    }
    return (int)len;
}

int main(int argc, char* argv[])
{
    do try {
        ::openSocket("192.168.6.30", "80");

        read(148); // Assume that data[] already has 364 bytes on the first call.
        for (;;)
        {
            read(512); // Full buffers on every subsequent call.
            // Do something with data[] here.
        }
    }
    catch (std::runtime_error) { } while (true);
}

do try catch while是必要的,因为错误只发生在我拔掉另一侧之后。在第二次调用read(148)之后,下一次读取(512)`失败。

[更新] 这不仅仅是transfer_exactly。使用transfer_at_least(512)我也会遇到同样的问题,一个多余的148字节读取。 (这两个应该表现相同,因为将至少 512字节读入缓冲区, 512字节无法读取更多或更少的字节)

1 个答案:

答案 0 :(得分:0)

现在通过忽略不正确的读取操作“解决”它。我很幸运,我可以处理未知数量的丢失数据,并在稍后重新同步流。但看起来我将不得不放弃Boost :: Asio,因为我再也无法容忍错过的数据了。