sockets - 如何模拟 boost::asio::write 超时

标签 sockets boost boost-asio tcp

我正在尝试用超时模拟 boost::asio::write。或者你可以说,我正在尝试使用带有超时的 boost::asio::async_write

如我所见,boost::asio::write 会阻塞,直到所有数据都在另一侧被写入和读取。这种功能当然需要超时。

那么,通读this simple answer hereRobert Hegner 演示如何使用 timeout 执行 boost::asio::async_read,我正在尝试采用相同的逻辑通过这样做来写:

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

问题:
该逻辑适用于读取似乎不适用于写入情况。 原因while (the_socket->get_io_service().run_one()) 在调用 the_socket->cancel() 两次后挂起。

但是,在读取的情况下,the_socket->cancel() 也被调用了两次并且不会在 while 的第 3 次循环中挂起并返回。因此,读取没有问题。

问题:
我对 超时逻辑 是否适用于 boost::asio::async_write 的理解有误吗?我认为同样的逻辑应该有效。我做错了什么,需要建议。

如果可能,还需要其他信息:
如果 boost::asio::read & boost::asio::write 有超时参数。我不会写这个额外的。似乎有很多要求 asio 人员在他们的同步读写功能中引入超时。喜欢this one这里。 asio 人员在不久的将来是否有解决此请求的余地?

我正在使用工作线程在同一个套接字上同步 boost::asio::read & boost::asio::write .我所缺少的只是这个超时功能。

环境:
我的代码在使用 C++ 14 编译器的 LinuxMacOSX 上运行。这个问题只涉及TCP 套接字

最佳答案

我已经编写了以下帮助程序来等待任何异步操作与超时同步¹:

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

此后我还使用完整的 TCP 客户端进行了演示:Boost::Asio synchronous client with timeout

该示例包括写操作并且已经过完全测试。

完整示例:

从原始帖子中获取“更好”的示例(FTP 客户端示例显示了更实际的使用模式):

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, '\n', 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;
    }
}

¹ 最初是为这个答案写的 https://stackoverflow.com/a/33445833/85371

关于sockets - 如何模拟 boost::asio::write 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47378022/

相关文章:

c++ - 如何获得指向 boost::variant 存储的指针?

c++ - 为 linux 扩展 boost.asio 文件输入/输出

c++ - Visual Studio 中的 Cygwin

c++ - 停止并等待文件传输协议(protocol),什么时候停止监听?

PHP 套接字服务器

c++ - boost::asio io_service 和 std::containers 的线程安全

c++ - 使用挂起的 read_async_some 关闭 boost::asio::serial_port

sockets - golang tcp 套接字在写入后不立即发送消息

c++使用 boost 测试

c++ - 在 LINUX 上使用 boost 时出现编译错误