diff --git a/examples/client/main.cpp b/examples/client/main.cpp index f581ea8..92c3fe9 100644 --- a/examples/client/main.cpp +++ b/examples/client/main.cpp @@ -310,6 +310,7 @@ void test_call_with_timeout() { void test_connect() { rpc_client client; client.enable_auto_reconnect(); //automatic reconnect + client.enable_auto_heartbeat(); //automatic heartbeat bool r = client.connect("127.0.0.1", 9000); int count = 0; while (true) { @@ -323,20 +324,20 @@ void test_connect() { std::this_thread::sleep_for(std::chrono::seconds(1)); } - { - rpc_client client; - bool r = client.connect("127.0.0.1", 9000); - int count = 0; - while (true) { - if (client.connect()) { - std::cout << "connected ok\n"; - break; - } - else { - std::cout << "connected failed: " << count++ << "\n"; - } - } - } + //{ + // rpc_client client; + // bool r = client.connect("127.0.0.1", 9000); + // int count = 0; + // while (true) { + // if (client.connect()) { + // std::cout << "connected ok\n"; + // break; + // } + // else { + // std::cout << "connected failed: " << count++ << "\n"; + // } + // } + //} std::string str; std::cin >> str; diff --git a/include/router.h b/include/router.h index 111dc9e..ea4b516 100644 --- a/include/router.h +++ b/include/router.h @@ -99,7 +99,7 @@ namespace rest_rpc { template static typename std::result_of, Args...)>::type call_member_helper( const F & f, Self * self, const std::index_sequence&, - std::tuple tup, std::weak_ptr ptr = nullptr) { + std::tuple tup, std::weak_ptr ptr = std::shared_ptr{ nullptr }) { return (*self.*f)(ptr, std::move(std::get(tup))...); } diff --git a/include/rpc_client.hpp b/include/rpc_client.hpp index ec0af89..369edbc 100644 --- a/include/rpc_client.hpp +++ b/include/rpc_client.hpp @@ -51,7 +51,7 @@ namespace rest_rpc { deadline_(ios_), body_(INIT_BUF_SIZE) { thd_ = std::make_shared([this] { ios_.run(); - }); + }); } rpc_client(const std::string& host, unsigned short port) : socket_(ios_), work_(ios_), @@ -118,8 +118,17 @@ namespace rest_rpc { return has_connected_; } - void enable_auto_reconnect() { - enable_reconnect_ = true; + void enable_auto_reconnect(bool enable = true) { + enable_reconnect_ = enable; + } + + void enable_auto_heartbeat(bool enable = true) { + if (enable) { + reset_deadline_timer(5); + } + else { + deadline_.cancel(); + } } void update_addr(const std::string& host, unsigned short port) { @@ -294,10 +303,14 @@ namespace rest_rpc { using message_type = std::pair; void reset_deadline_timer(size_t timeout) { deadline_.expires_from_now(std::chrono::seconds(timeout)); - deadline_.async_wait([this](const boost::system::error_code& ec) { + deadline_.async_wait([this, timeout](const boost::system::error_code& ec) { if (!ec) { - socket_.close(); + if (has_connected_) { + write(0, buffer_type(0)); + } } + + reset_deadline_timer(timeout); }); }