Skip to content

Commit

Permalink
[Server] Now handles client socket disconnection properly.
Browse files Browse the repository at this point in the history
  • Loading branch information
Unarelith committed Mar 6, 2020
1 parent d883467 commit 5307838
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
26 changes: 17 additions & 9 deletions server/source/network/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions server/source/network/Server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ class Server {
void handleNewConnections();
void handleClientMessages();

void disconnectClient(ClientInfo &client);

bool m_isRunning = false;
bool m_isSingleplayer = false;

Expand Down

0 comments on commit 5307838

Please sign in to comment.