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 -