From 53078388b40b727a02a96507abc6a5a8a47f2f2e Mon Sep 17 00:00:00 2001 From: Quentin Bazin Date: Fri, 6 Mar 2020 14:14:11 +0100 Subject: [PATCH] [Server] Now handles client socket disconnection properly. --- server/source/network/Server.cpp | 26 +++++++++++++++++--------- server/source/network/Server.hpp | 2 ++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/server/source/network/Server.cpp b/server/source/network/Server.cpp index f76fe061e..76757ba71 100644 --- a/server/source/network/Server.cpp +++ b/server/source/network/Server.cpp @@ -126,7 +126,8 @@ void Server::handleClientMessages() { ClientInfo &client = m_info.clients()[i]; if (m_selector.isReady(*client.tcpSocket)) { sf::Packet packet; - if (client.tcpSocket->receive(packet) == sf::Socket::Done) { + sf::Socket::Status status = client.tcpSocket->receive(packet); + if (status == sf::Socket::Done) { Network::Command command; packet >> command; @@ -138,23 +139,30 @@ void Server::handleClientMessages() { it.second(client, packet); if (command == Network::Command::ClientDisconnect) { - m_selector.remove(*client.tcpSocket); - m_info.removeClient(client.id); - - if (m_isSingleplayer && m_info.clients().size() == 0) { - m_tcpListener.close(); - m_isRunning = false; - } - + disconnectClient(client); --i; } } } } + else if (status == sf::Socket::Disconnected) { + disconnectClient(client); + --i; + } } } } +void Server::disconnectClient(ClientInfo &client) { + m_selector.remove(*client.tcpSocket); + m_info.removeClient(client.id); + + if (m_isSingleplayer && m_info.clients().size() == 0) { + m_tcpListener.close(); + m_isRunning = false; + } +} + void Server::sendToAllClients(sf::Packet &packet) { for (ClientInfo &client : m_info.clients()) { client.tcpSocket->send(packet); diff --git a/server/source/network/Server.hpp b/server/source/network/Server.hpp index 7bf1e9411..25eae5a3d 100644 --- a/server/source/network/Server.hpp +++ b/server/source/network/Server.hpp @@ -66,6 +66,8 @@ class Server { void handleNewConnections(); void handleClientMessages(); + void disconnectClient(ClientInfo &client); + bool m_isRunning = false; bool m_isSingleplayer = false;