簡體   English   中英

boost:asio :: read或boost:asio :: async_read超時

[英]boost:asio::read or boost:asio::async_read with timeout

是。 我知道在boost::asio time_out周圍存在一些問題。 我的問題可能對於asio家伙來說太簡單了,無法在這里解決。

我正在TCP協議上使用boost::asio ,以boost::asio速度連續不斷地通過網絡讀取數據。

在while循環中,從工作程序std::thread連續調用以下函數ReadData()

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

工作正常。 返回數據。 一切都很好。

我想要的就是對 time boost::asio::read使用time_out 我了解到我需要將boost::asio::async_readboost::asio::async_wait以使time_out技術起作用。

一個提升示例建議使用boost::asio::async_read_until嗎?

我應該使用boost::asio::async_read還是boost::asio::async_read_until嗎?

我是否使用boost::asio::async_readboost::asio::async_read_untilboost::asio::read boost::asio::async_read_until 但是我希望在對方法ReadData的調用中觸發並完成asio::read調用,以使客戶端代碼不會受到影響。

我該如何實現? 請建議

好的,這樣的事情應該適合您的目的:

理由:

您似乎想使用阻止操作。 既然是這樣,您很有可能沒有運行線程來泵送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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM