Skip to content

Commit

Permalink
add wait_conn
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos committed Mar 27, 2019
1 parent 17598a5 commit 2eb0d4f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
7 changes: 5 additions & 2 deletions examples/client/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 15 additions & 1 deletion include/async_client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<void(boost::system::error_code)> f) {
err_cb_ = std::move(f);
}
Expand Down Expand Up @@ -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_;
Expand All @@ -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_;

Expand Down

0 comments on commit 2eb0d4f

Please sign in to comment.