From 8335769cc844e9a93f89526f0bfffe4aba178907 Mon Sep 17 00:00:00 2001 From: Kieran Kihn <114803508+kierankihn@users.noreply.github.com> Date: Thu, 4 Dec 2025 17:17:24 +0800 Subject: [PATCH] feat(network): enhance `NetworkClient` with run and stop methods - Added `run` and `stop` methods to manage the IO context lifecycle. - Updated `send` to post messages to the IO context. --- src/network/NetworkClient.cpp | 18 ++++++++++++++---- src/network/NetworkClient.h | 13 +++++++++++-- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/network/NetworkClient.cpp b/src/network/NetworkClient.cpp index 00dafb0..f3f28f1 100644 --- a/src/network/NetworkClient.cpp +++ b/src/network/NetworkClient.cpp @@ -15,18 +15,28 @@ namespace UNO::NETWORK { void NetworkClient::connect(const std::string &host, uint16_t port) { + io_context_.restart(); asio::ip::tcp::socket socket(io_context_); - asio::ip::tcp::resolver resolver(io_context_); auto endpoints = resolver.resolve(host, std::to_string(port)); - + asio::connect(socket, endpoints); this->session_ = std::make_shared(std::move(socket)); this->session_->start(callback_); } - void NetworkClient::send(const std::string &message) const + void NetworkClient::send(const std::string &message) { - this->session_->send(message); + asio::post(io_context_, [session = this->session_, message]() { session->send(message); }); + } + + void NetworkClient::run() + { + this->io_context_.run(); + } + + void NetworkClient::stop() + { + this->io_context_.stop(); } } // namespace UNO::NETWORK diff --git a/src/network/NetworkClient.h b/src/network/NetworkClient.h index eeedca9..8dbf4f0 100644 --- a/src/network/NetworkClient.h +++ b/src/network/NetworkClient.h @@ -32,8 +32,17 @@ namespace UNO::NETWORK { * 向服务端发送消息 * @param message 要发送的消息 */ - void send(const std::string &message) const; + void send(const std::string &message); + + /** + * 启动网络事件循环 + */ + void run(); + + /** + * 停止网络事件循环 + */ + void stop(); }; } // namespace UNO::NETWORK -