From 85175331f09f5d81ab2a6b45d8a92981ba2e1e62 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Wed, 6 Mar 2019 15:12:24 +0800 Subject: [PATCH] add async_client --- test_client/async_client.hpp | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 test_client/async_client.hpp diff --git a/test_client/async_client.hpp b/test_client/async_client.hpp new file mode 100644 index 0000000..2a7b1c4 --- /dev/null +++ b/test_client/async_client.hpp @@ -0,0 +1,78 @@ +#pragma once +#include +#include +using boost::asio::ip::tcp; +#include "../codec.h" +using namespace rest_rpc; +using namespace rest_rpc::rpc_service; + +class async_client : private boost::noncopyable { +public: + async_client(const std::string& host, unsigned short port) : socket_(ios_), work_(ios_), + connect_timer_(ios_), host_(host), port_(port) { + } + + void set_timeout(int milliseconds) { + assert(milliseconds > 0); + timeout_ = milliseconds; + } + + void set_reconnect_count(int reconnect_count) { + reconnect_cnt_ = reconnect_count; + } + + void connect() { + reset_connect_timer(); + auto addr = boost::asio::ip::make_address_v4(host_); + socket_.async_connect({ addr, port_ }, [this](const boost::system::error_code& ec) { + if (ec) { + std::cout << ec.message() << std::endl; + has_connected_ = false; + if (reconnect_cnt_ == 0) { + return; + } + + if (reconnect_cnt_ > 0) { + reconnect_cnt_--; + } + + socket_ = decltype(socket_)(ios_); + connect(); + } + else { + has_connected_ = true; + std::cout << "connect "<< host_<<" "<