boost:asio :: read或boost:asio :: async_read with timeout

时间:2017-04-03 19:36:20

标签: c++ boost-asio asio

是。我知道time_out中有boost::asio个问题。对于asio人来说,我的问题可能太简单了。

我在TCP协议上使用boost::asio以尽可能快的速度在网络中连续读取数据。

跟随函数ReadData()在while循环中从worker std::thread连续调用。

std::size_t ReadData(std::vector<unsigned char> & buffer, unsigned int size_to_read) {

 boost::system::error_code error_code;
 buffer.resize(size_to_read);

 // Receive body
 std::size_t bytes_read = boost::asio::read(*m_socket, boost::asio::buffer(buffer), error_code);

 if (bytes_read == 0) {
   // log error
   return;
 }

 return bytes_read;
}

一切正常。返回数据。一切都很好。

我想要的是boost::asio::read使用 time_out 。我了解到我需要使用boost::asio::async_readboost::asio::async_wait来使用time_out技术。

一个boost example建议使用boost::asio::async_read_until

我应该使用boost::asio::async_read还是boost::asio::async_read_until

使用boost::asio::async_readboost::asio::async_read_until还是boost::asio::read并不重要。但是我想要触发asio::read来电。在对我的方法ReadData的调用中完成,以便客户端代码不会受到影响。

我怎样才能做到这一点?请建议

1 个答案:

答案 0 :(得分:1)

好的,这样的事情应该适合你的目的:

理由:

您似乎想要使用阻止操作。既然如此,你很可能没有运行线程来抽取io循环。

因此,我们在套接字的io循环上启动两个同时执行的异步任务,然后生成一个线程:

a)重置(实际重启)循环,以防它已经用尽

b)运行循环到耗尽(我们可以在这里更聪明,只运行它,直到处理程序表明已经满足某些条件,但这是另一天的教训)

#include <type_traits>

template<class Stream, class ConstBufferSequence, class Handler>
auto async_read_with_timeout(Stream& stream, ConstBufferSequence&& sequence, std::size_t millis, Handler&& handler)
{
    using handler_type = std::decay_t<Handler>;
    using buffer_sequence_type = std::decay_t<ConstBufferSequence>;
    using stream_type = Stream;

    struct state_machine : std::enable_shared_from_this<state_machine>
    {
        state_machine(stream_type& stream, buffer_sequence_type sequence, handler_type handler)
                : stream_(stream)
                , sequence_(std::move(sequence))
                , handler_(std::move(handler))
        {}
        void start(std::size_t millis)
        {
            timer_.expires_from_now(boost::posix_time::milliseconds(millis));
            timer_.async_wait(strand_.wrap([self = this->shared_from_this()](auto&& ec) {
                self->handle_timeout(ec);
            }));
            boost::asio::async_read(stream_, sequence_,
                                    strand_.wrap([self = this->shared_from_this()](auto&& ec, auto size){
                self->handle_read(ec, size);
            }));
        }

        void handle_timeout(boost::system::error_code const& ec)
        {
            if (not ec and not completed_)
            {
                boost::system::error_code sink;
                stream_.cancel(sink);
            }
        }

        void handle_read(boost::system::error_code const& ec, std::size_t size)
        {
            assert(not completed_);
            boost::system::error_code sink;
            timer_.cancel(sink);
            completed_ = true;
            handler_(ec, size);
        }

        stream_type& stream_;
        buffer_sequence_type sequence_;
        handler_type handler_;
        boost::asio::io_service::strand strand_ { stream_.get_io_service() };
        boost::asio::deadline_timer timer_ { stream_.get_io_service() };
        bool completed_ = false;
    };

    auto psm = std::make_shared<state_machine>(stream,
                                               std::forward<ConstBufferSequence>(sequence),
                                               std::forward<Handler>(handler));
    psm->start(millis);
}

std::size_t ReadData(boost::asio::ip::tcp::socket& socket,
                     std::vector<unsigned char> & buffer,
                     unsigned int size_to_read,
                     boost::system::error_code& ec) {

    buffer.resize(size_to_read);

    ec.clear();
    std::size_t bytes_read = 0;
    auto& executor = socket.get_io_service();
    async_read_with_timeout(socket, boost::asio::buffer(buffer),
                            2000, // 2 seconds for example
                            [&](auto&& err, auto size){
        ec = err;
        bytes_read = size;
    });

    // todo: use a more scalable executor than spawning threads
    auto future = std::async(std::launch::async, [&] {
        if (executor.stopped()) {
            executor.reset();
        }
        executor.run();
    });
    future.wait();

    return bytes_read;
}