From c26fcfe033d5eefb44730738ac4f1a43faa841eb Mon Sep 17 00:00:00 2001 From: qicosmos Date: Thu, 9 Oct 2025 16:48:40 +0800 Subject: [PATCH] fix close --- include/rest_rpc/rpc_connection.hpp | 3 +-- include/rest_rpc/rpc_server.hpp | 12 ++++++++++-- tests/test_rest_rpc.cpp | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/include/rest_rpc/rpc_connection.hpp b/include/rest_rpc/rpc_connection.hpp index d260d6b..e91bc7c 100644 --- a/include/rest_rpc/rpc_connection.hpp +++ b/include/rest_rpc/rpc_connection.hpp @@ -51,7 +51,6 @@ public: : socket_(std::move(socket)), conn_id_(conn_id), router_(router), cross_ending_(cross_ending) {} - ~rpc_connection() { close(); } asio::awaitable start() { rest_rpc_header header; auto self = this->shared_from_this(); @@ -164,7 +163,7 @@ public: std::error_code ec; socket_.shutdown(asio::socket_base::shutdown_both, ec); socket_.close(ec); - REST_LOG_INFO << "close socket " << need_cb; + REST_LOG_INFO << "close connection, id " << conn_id_; if (need_cb && quit_cb_) { quit_cb_(conn_id_); } diff --git a/include/rest_rpc/rpc_server.hpp b/include/rest_rpc/rpc_server.hpp index 29d9c75..c7a6597 100644 --- a/include/rest_rpc/rpc_server.hpp +++ b/include/rest_rpc/rpc_server.hpp @@ -195,8 +195,16 @@ private: auto mtx = weak.lock(); if (mtx) { std::scoped_lock lock(*mtx); - if (!conns_.empty()) - conns_.erase(id); + if (!conns_.empty()) { + std::erase_if(conns_, [id](const auto &pair) { + if (pair.first == id) { + pair.second->close(false); + return true; + } + + return false; + }); + } } }); diff --git a/tests/test_rest_rpc.cpp b/tests/test_rest_rpc.cpp index e2c85b3..72538f7 100644 --- a/tests/test_rest_rpc.cpp +++ b/tests/test_rest_rpc.cpp @@ -210,6 +210,26 @@ asio::awaitable test_router() { TEST_CASE("test router") { sync_wait(get_global_executor(), test_router()); } +TEST_CASE("test rpc_connection") { + uint64_t conn_id = 999; + size_t num_thread = 4; + asio::io_context io_ctx; + tcp_socket socket(io_ctx); + bool cross_ending_ = false; + rpc_router router; + dummy d{}; + router.register_handler<&dummy::add>(&d); + auto conn = std::make_shared(std::move(socket), conn_id, + router, cross_ending_); + CHECK_EQ(conn->id(), conn_id); + conn->set_check_timeout(true); + conn->set_last_time(); + auto last_rw_time = conn->get_last_rwtime(); + std::cout << "topic_id: " << conn->topic_id() << std::endl; + conn->close(); + io_ctx.run(); +} + TEST_CASE("test context pool") { io_context_pool pool(0); CHECK(pool.size() == 1);