我正在尝试用超时模拟 boost::asio::write
。或者你可以说,我正在尝试使用带有超时的 boost::asio::async_write
。
如我所见,boost::asio::write
会阻塞,直到所有数据都在另一侧被写入和读取。这种功能当然需要超时。
那么,通读this simple answer here由 Robert 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 编译器的 Linux
和 MacOSX
上运行。这个问题只涉及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 客户端示例显示了更实际的使用模式):
#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/