From 2eb0d4f7df1c81c38a181259aa78cd93fd581dda Mon Sep 17 00:00:00 2001 From: qicosmos Date: Wed, 27 Mar 2019 10:00:16 +0800 Subject: [PATCH] add wait_conn --- examples/client/main.cpp | 7 +++++-- include/async_client.hpp | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/examples/client/main.cpp b/examples/client/main.cpp index 13bf698..76e096d 100644 --- a/examples/client/main.cpp +++ b/examples/client/main.cpp @@ -98,8 +98,11 @@ struct dummy { void test_async_client() { async_client client("127.0.0.1", 9000); client.connect(); -// std::string str1; -// std::cin >> str1; + bool r = client.wait_conn(1); + if (!r) { + std::cout << "connect timeout" << std::endl; + return; + } client.set_error_callback([] (boost::system::error_code ec){ std::cout << ec.message() << std::endl; diff --git a/include/async_client.hpp b/include/async_client.hpp index 8c7e938..276ed3c 100644 --- a/include/async_client.hpp +++ b/include/async_client.hpp @@ -86,11 +86,23 @@ namespace rest_rpc { has_connected_ = true; deadline_.cancel(); do_read(); + conn_cond_.notify_one(); std::cout << "connect " << host_ << " " << port_ << std::endl; } }); } + bool wait_conn(size_t timeout) { + if (has_connected_) { + return true; + } + + std::unique_lock lock(conn_mtx_); + bool result = conn_cond_.wait_for(lock, std::chrono::seconds(timeout), + [this] {return has_connected_; }); + return result; + } + void set_error_callback(std::function f) { err_cb_ = std::move(f); } @@ -379,7 +391,6 @@ namespace rest_rpc { } } - bool has_connected_ = false; boost::asio::io_service ios_; tcp::socket socket_; boost::asio::io_service::work work_; @@ -391,6 +402,9 @@ namespace rest_rpc { size_t connect_timeout_ = 2;//s size_t wait_timeout_ = 2;//s int reconnect_cnt_ = -1; + bool has_connected_ = false; + std::mutex conn_mtx_; + std::condition_variable conn_cond_; boost::asio::deadline_timer deadline_;