mirror of
https://github.com/kierankihn/uno-game.git
synced 2025-12-27 02:13:18 +08:00
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:
@@ -16,11 +16,20 @@ namespace UNO::NETWORK {
|
|||||||
|
|
||||||
void NetworkClient::connect(const std::string &host, uint16_t port)
|
void NetworkClient::connect(const std::string &host, uint16_t port)
|
||||||
{
|
{
|
||||||
|
this->disconnect();
|
||||||
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.begin(), endpoints.end());
|
asio::connect(socket_, endpoints.begin(), endpoints.end());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void NetworkClient::disconnect()
|
||||||
|
{
|
||||||
|
if (socket_.is_open()) {
|
||||||
|
this->socket_.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void NetworkClient::send(const std::string &message)
|
void NetworkClient::send(const std::string &message)
|
||||||
{
|
{
|
||||||
size_t length = message.size();
|
size_t length = message.size();
|
||||||
|
|||||||
@@ -26,6 +26,11 @@ namespace UNO::NETWORK {
|
|||||||
*/
|
*/
|
||||||
void connect(const std::string &host, uint16_t port);
|
void connect(const std::string &host, uint16_t port);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭到服务端的连接
|
||||||
|
*/
|
||||||
|
void disconnect();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 向服务端发送消息
|
* 向服务端发送消息
|
||||||
* @param message 要发送的消息
|
* @param message 要发送的消息
|
||||||
|
|||||||
Reference in New Issue
Block a user