feat(network): add async connect with onConnect callback

- Replaced synchronous `connect` with asynchronous connection logic.
- Introduced `onConnect` callback to handle connection success events.
- Ensured proper `io_context` work guard management.
This commit is contained in:
Kieran Kihn
2025-12-09 19:42:26 +08:00
parent d5f996df6c
commit 98a7ef7d41
2 changed files with 26 additions and 9 deletions

View File

@@ -7,21 +7,34 @@
#include "NetworkClient.h" #include "NetworkClient.h"
#include <asio/connect.hpp> #include <asio/connect.hpp>
#include <iostream>
#include <memory> #include <memory>
#include <utility> #include <utility>
namespace UNO::NETWORK { namespace UNO::NETWORK {
NetworkClient::NetworkClient(std::function<void(std::string)> callback) : callback_(std::move(callback)) {} NetworkClient::NetworkClient(std::function<void()> onConnect, std::function<void(std::string)> callback) :
onConnected_(std::move(onConnect)), callback_(std::move(callback)), workGuard_(asio::make_work_guard(io_context_))
{
}
void NetworkClient::connect(const std::string &host, uint16_t port) void NetworkClient::connect(const std::string &host, uint16_t port)
{ {
io_context_.restart(); auto socket = std::make_shared<asio::ip::tcp::socket>(io_context_);
asio::ip::tcp::socket socket(io_context_); auto resolver = std::make_shared<asio::ip::tcp::resolver>(io_context_);
asio::ip::tcp::resolver resolver(io_context_); resolver->async_resolve(host,
auto endpoints = resolver.resolve(host, std::to_string(port)); std::to_string(port),
asio::connect(socket, endpoints); [this, resolver, socket](const asio::error_code &ec, const asio::ip::tcp::resolver::results_type &results) {
this->session_ = std::make_shared<Session>(std::move(socket)); if (!ec) {
this->session_->start(callback_); asio::async_connect(
*socket, results, [this, socket](const asio::error_code &ec, const asio::ip::tcp::endpoint &) {
if (!ec) {
this->session_ = std::make_shared<Session>(std::move(*socket));
this->session_->start(callback_);
this->onConnected_();
}
});
}
});
} }
@@ -37,6 +50,7 @@ namespace UNO::NETWORK {
void NetworkClient::stop() void NetworkClient::stop()
{ {
this->workGuard_.reset();
this->io_context_.stop(); this->io_context_.stop();
} }
} // namespace UNO::NETWORK } // namespace UNO::NETWORK

View File

@@ -14,12 +14,15 @@ namespace UNO::NETWORK {
class NetworkClient { class NetworkClient {
private: private:
asio::io_context io_context_; asio::io_context io_context_;
asio::executor_work_guard<asio::io_context::executor_type> workGuard_;
std::function<void()> onConnected_;
std::function<void(std::string)> callback_; std::function<void(std::string)> callback_;
std::shared_ptr<Session> session_; std::shared_ptr<Session> session_;
public: public:
explicit NetworkClient(std::function<void(std::string)> callback); NetworkClient(std::function<void()> onConnect, std::function<void(std::string)> callback);
/** /**
* 连接到服务端 * 连接到服务端