mirror of
https://github.com/kierankihn/uno-game.git
synced 2025-12-27 02:13:18 +08:00
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:
@@ -15,18 +15,28 @@ namespace UNO::NETWORK {
|
|||||||
|
|
||||||
void NetworkClient::connect(const std::string &host, uint16_t port)
|
void NetworkClient::connect(const std::string &host, uint16_t port)
|
||||||
{
|
{
|
||||||
|
io_context_.restart();
|
||||||
asio::ip::tcp::socket socket(io_context_);
|
asio::ip::tcp::socket socket(io_context_);
|
||||||
|
|
||||||
asio::ip::tcp::resolver resolver(io_context_);
|
asio::ip::tcp::resolver resolver(io_context_);
|
||||||
auto endpoints = resolver.resolve(host, std::to_string(port));
|
auto endpoints = resolver.resolve(host, std::to_string(port));
|
||||||
|
asio::connect(socket, endpoints);
|
||||||
this->session_ = std::make_shared<Session>(std::move(socket));
|
this->session_ = std::make_shared<Session>(std::move(socket));
|
||||||
this->session_->start(callback_);
|
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
|
} // namespace UNO::NETWORK
|
||||||
|
|||||||
@@ -32,8 +32,17 @@ namespace UNO::NETWORK {
|
|||||||
* 向服务端发送消息
|
* 向服务端发送消息
|
||||||
* @param message 要发送的消息
|
* @param message 要发送的消息
|
||||||
*/
|
*/
|
||||||
void send(const std::string &message) const;
|
void send(const std::string &message);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动网络事件循环
|
||||||
|
*/
|
||||||
|
void run();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停止网络事件循环
|
||||||
|
*/
|
||||||
|
void stop();
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace UNO::NETWORK
|
} // namespace UNO::NETWORK
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user