From 913c896041198be91c366820bd9cc97543bc16d7 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Sat, 27 Jan 2024 10:04:37 +0800 Subject: [PATCH] fix reconnect --- include/rest_rpc/rpc_client.hpp | 8 +++---- tests/test_rest_rpc.cpp | 41 +++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/include/rest_rpc/rpc_client.hpp b/include/rest_rpc/rpc_client.hpp index e14529e..d1b8eb4 100644 --- a/include/rest_rpc/rpc_client.hpp +++ b/include/rest_rpc/rpc_client.hpp @@ -100,7 +100,7 @@ public: std::promise promise; ios_.post([this, &promise] { close(); - stop_timer_ = true; + stop_client_ = true; std::error_code ec; deadline_.cancel(ec); promise.set_value(); @@ -388,7 +388,7 @@ private: assert(port_ != 0); auto addr = asio::ip::address::from_string(host_); socket_.async_connect({addr, port_}, [this](const asio::error_code &ec) { - if (has_connected_) { + if (has_connected_ || stop_client_) { return; } @@ -429,7 +429,7 @@ private: } void reset_deadline_timer(size_t timeout) { - if (stop_timer_) { + if (stop_client_) { return; } @@ -848,7 +848,7 @@ private: bool has_wait_ = false; asio::steady_timer deadline_; - bool stop_timer_ = false; + bool stop_client_ = false; struct client_message_type { std::uint64_t req_id; diff --git a/tests/test_rest_rpc.cpp b/tests/test_rest_rpc.cpp index 09dc9dc..27c2957 100644 --- a/tests/test_rest_rpc.cpp +++ b/tests/test_rest_rpc.cpp @@ -1,17 +1,15 @@ +#include "doctest/doctest.h" #include #include #include -#include #include -#include "doctest/doctest.h" +#include using namespace rest_rpc; using namespace rpc_service; struct dummy { - int add(rpc_conn conn, int a, int b) { - return a + b; - } + int add(rpc_conn conn, int a, int b) { return a + b; } }; std::string echo(rpc_conn conn, const std::string &src) { return src; } @@ -29,6 +27,39 @@ void hello(rpc_conn conn, const std::string &str) { std::cout << "hello " << str << std::endl; } +TEST_CASE("test_client_reconnect") { + rpc_client client; + client.enable_auto_reconnect(); // automatic reconnect + client.enable_auto_heartbeat(); // automatic heartbeat + client.set_error_callback([](asio::error_code ec) { + std::cout << "line: " << __LINE__ << ", 11msg: " << ec.message() + << std::endl; + }); + client.connect("127.0.0.1", 9000); + + rpc_server server(9000, std::thread::hardware_concurrency()); + dummy d; + server.register_handler("add", &dummy::add, &d); + server.async_run(); + + int count = 0; + while (true) { + if (client.has_connected()) { + try { + auto result = client.call("add", 1, 2); + CHECK_EQ(result, 3); + break; + } catch (const std::exception &ex) { + std::cout << ex.what() << std::endl; + } + } else { + // count++; + std::cout << "connected failed: " << count++ << "\n"; + } + std::this_thread::sleep_for(std::chrono::seconds(1)); + } +} + TEST_CASE("test_client_default_constructor") { rpc_server server(9000, std::thread::hardware_concurrency()); dummy d;