fix(network): ensure disconnect before connect in NetworkClient

- Added `disconnect` method to gracefully close existing connections before establishing a new one.
- Updated `connect` to call `disconnect` to prevent resource conflicts.
This commit is contained in:
Kieran Kihn
2025-11-29 18:51:58 +08:00
parent 12d1d6c93f
commit c2ccaaf17e
2 changed files with 14 additions and 0 deletions

View File

@@ -16,11 +16,20 @@ namespace UNO::NETWORK {
void NetworkClient::connect(const std::string &host, uint16_t port)
{
this->disconnect();
asio::ip::tcp::resolver resolver(io_context_);
auto endpoints = resolver.resolve(host, std::to_string(port));
asio::connect(socket_, endpoints.begin(), endpoints.end());
}
void NetworkClient::disconnect()
{
if (socket_.is_open()) {
this->socket_.close();
}
}
void NetworkClient::send(const std::string &message)
{
size_t length = message.size();

View File

@@ -26,6 +26,11 @@ namespace UNO::NETWORK {
*/
void connect(const std::string &host, uint16_t port);
/**
* 关闭到服务端的连接
*/
void disconnect();
/**
* 向服务端发送消息
* @param message 要发送的消息