diff --git a/include/rest_rpc/rpc_client.hpp b/include/rest_rpc/rpc_client.hpp index 0c9acb8..e14529e 100644 --- a/include/rest_rpc/rpc_client.hpp +++ b/include/rest_rpc/rpc_client.hpp @@ -67,14 +67,16 @@ const constexpr size_t DEFAULT_TIMEOUT = 5000; // milliseconds class rpc_client : private asio::noncopyable { public: rpc_client() - : socket_(ios_), work_(ios_), deadline_(ios_), body_(INIT_BUF_SIZE) { + : socket_(ios_), work_(std::make_shared(ios_)), + deadline_(ios_), body_(INIT_BUF_SIZE) { thd_ = std::make_shared([this] { ios_.run(); }); } rpc_client(client_language_t client_language, std::function on_result_received_callback) - : socket_(ios_), work_(ios_), deadline_(ios_), body_(INIT_BUF_SIZE), + : socket_(ios_), work_(std::make_shared(ios_)), + deadline_(ios_), body_(INIT_BUF_SIZE), client_language_(client_language), on_result_received_callback_(std::move(on_result_received_callback)) { thd_ = std::make_shared([this] { ios_.run(); }); @@ -87,8 +89,9 @@ class rpc_client : private asio::noncopyable { std::function on_result_received_callback, std::string host, unsigned short port) - : socket_(ios_), work_(ios_), deadline_(ios_), host_(std::move(host)), - port_(port), body_(INIT_BUF_SIZE), client_language_(client_language), + : socket_(ios_), work_(std::make_shared(ios_)), + deadline_(ios_), host_(std::move(host)), port_(port), + body_(INIT_BUF_SIZE), client_language_(client_language), on_result_received_callback_(std::move(on_result_received_callback)) { thd_ = std::make_shared([this] { ios_.run(); }); } @@ -97,6 +100,9 @@ class rpc_client : private asio::noncopyable { std::promise promise; ios_.post([this, &promise] { close(); + stop_timer_ = true; + std::error_code ec; + deadline_.cancel(ec); promise.set_value(); }); promise.get_future().wait(); @@ -320,7 +326,7 @@ class rpc_client : private asio::noncopyable { void stop() { if (thd_ != nullptr) { - ios_.stop(); + work_ = nullptr; if (thd_->joinable()) { thd_->join(); } @@ -423,6 +429,10 @@ class rpc_client : private asio::noncopyable { } void reset_deadline_timer(size_t timeout) { + if (stop_timer_) { + return; + } + deadline_.expires_from_now(std::chrono::seconds(timeout)); deadline_.async_wait([this, timeout](const asio::error_code &ec) { if (!ec) { @@ -825,7 +835,7 @@ class rpc_client : private asio::noncopyable { std::unique_ptr> ssl_stream_; std::function ssl_context_callback_; #endif - asio::io_context::work work_; + std::shared_ptr work_; std::shared_ptr thd_ = nullptr; std::string host_; @@ -838,6 +848,7 @@ class rpc_client : private asio::noncopyable { bool has_wait_ = false; asio::steady_timer deadline_; + bool stop_timer_ = false; struct client_message_type { std::uint64_t req_id;