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.
This commit is contained in:
Kieran Kihn
2025-12-04 17:17:24 +08:00
parent 024f99fc01
commit 8335769cc8
2 changed files with 25 additions and 6 deletions

View File

@@ -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<Session>(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

View File

@@ -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