Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

sockets - How to simulate boost::asio::write with a timeout

I am trying to simulate boost::asio::write with timeout. Or you can say, I am trying to use boost::asio::async_write with a timeout.

As I see, boost::asio::write blocks until all data has been written & read on the other side. This kind of functionality certainly requires a timeout.

So, Reading through this simple answer here by Robert Hegner which demostrates how to do a boost::asio::async_read with timeout, I am trying adapt the same logic for write by doing so:

size_t write_data_with_time_out() {

    long time_out_secs = 2;

    boost::optional<boost::system::error_code> timer_result;
    boost::asio::deadline_timer timer(the_socket->get_io_service(), boost::posix_time::seconds(time_out_secs));

    timer.expires_from_now();
    timer.async_wait([&timer_result] (const boost::system::error_code& error) {
        timer_result.reset(error);
    });

    boost::optional<boost::system::error_code> write_result;
    size_t bytes_sent = 0;
    boost::asio::async_write(*the_socket, boost::asio::buffer(the_buffer_to_write, the_buffer_to_write.size()), [&write_result, &bytes_sent] (const boost::system::error_code& error, auto size_received) {

        write_result.reset(error);
        bytes_sent = size_received;
    });

    the_socket->get_io_service().reset();
    while (the_socket->get_io_service().run_one()) {

        if (write_result) {
            timer.cancel();
        }
        else if (timer_result) {
            the_socket->cancel();
        }
    }

    if (*write_result) {
        return 0;
    }

    return bytes_sent;
}

Problem:
The logic works great for read but does not seem to work for write case. Reason is that while (the_socket->get_io_service().run_one()) gets hung after calling the_socket->cancel() twice.

However, in the read case also the_socket->cancel() is called twice & does not hang on the 3rd loop over of the while & returns out. Hence no issues with read.

Question:
Is my understanding wrong that same timeout logic would work for boost::asio::async_write case? I think this same logic should work. There is something wrong I am doing which is what I need a suggestion on.

Additional info required if possible:
if boost::asio::read & boost::asio::write had a timeout parameter. I would not have been writing this extra. Seems like there have been a lot of requests to asio guys to introduce a timeout in their sync read & write functions. Like this one here. Is there any scope for asio guys to address this request in near future?

I am doing a sync boost::asio::read & boost::asio::write on the same socket using a worker thread for which this works superb. All I am missing is this timeout functionality.

Environment:
My code runs on Linux & MacOSX with C++ 14 compiler. This question only concerns TCP sockets.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I've written the following helper to await any async operation synchronously with a timeout1:

template<typename AllowTime> void await_operation(AllowTime const& deadline_or_duration) {
    using namespace boost::asio;

    ioservice.reset();
    {
        high_resolution_timer tm(ioservice, deadline_or_duration);
        tm.async_wait([this](error_code ec) { if (ec != error::operation_aborted) socket.cancel(); });
        ioservice.run_one();
    }
    ioservice.run();
}

I've since also demoed that with a full on TCP client: Boost::Asio synchronous client with timeout

The sample includes write operations and has been completely tested.

Complete Sample:

Taking the "nicer" example from the original post (the FTP client example shows more realistic usage patterns):

Live On Coliru

#ifndef __TCPCLIENT_H__
#define __TCPCLIENT_H__

#include <boost/asio.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <iostream>

class TCPClient {
public:
    void        disconnect();
    void        connect(const std::string& address, const std::string& port);
    std::string sendMessage(const std::string& msg);

private:
    using error_code = boost::system::error_code;

    template<typename AllowTime> void await_operation(AllowTime const& deadline_or_duration) {
        using namespace boost::asio;

        ioservice.reset();
        {
            high_resolution_timer tm(ioservice, deadline_or_duration);
            tm.async_wait([this](error_code ec) { if (ec != error::operation_aborted) socket.cancel(); });
            ioservice.run_one();
        }
        ioservice.run();
    }

    struct raise {
        template <typename... A> void operator()(error_code ec, A...) const {
            if (ec) throw std::runtime_error(ec.message()); 
        }
    };

    boost::asio::io_service      ioservice { };
    boost::asio::ip::tcp::socket socket { ioservice };
};

inline void TCPClient::disconnect() {
    using namespace boost::asio;

    if (socket.is_open()) {
        try {
            socket.shutdown(ip::tcp::socket::shutdown_both);
            socket.close();
        }
        catch (const boost::system::system_error& e) {
            // ignore
            std::cerr << "ignored error " << e.what() << std::endl;
        }
    }
}

inline void TCPClient::connect(const std::string& address, const std::string& port) {
    using namespace boost::asio;

    async_connect(socket, ip::tcp::resolver(ioservice).resolve({address, port}), raise());

    await_operation(std::chrono::seconds(6));
}

inline std::string TCPClient::sendMessage(const std::string& msg) {
    using namespace boost::asio;

    streambuf response;
    async_read_until(socket, response, '
', raise());

    await_operation(std::chrono::system_clock::now() + std::chrono::seconds(4));

    return {std::istreambuf_iterator<char>(&response), {}};
}
#endif

#include <iostream>

//#include "TCPClient.hpp"

int main(/*int argc, char* argv[]*/) {
    TCPClient client;
    try {
        client.connect("127.0.0.1", "27015");
        std::cout << "Response: " << client.sendMessage("Hello!") << std::endl;
    }
    catch (const boost::system::system_error& e) {
        std::cerr << e.what() << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
}

1 originally written for this answer https://stackoverflow.com/a/33445833/85371


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...