Fix getPeerCount() to return correct number of peers

Calling getPeerCount() used to return the maximum number
of peers on the host, no matter how many peers were actually
connected. Changing this function to count the elements within
the "players" vector returns the correct peer count.

However calling getPeerCount() within the "onDisconnect" callback
results in an extra peer being present due to the "players"
vector only being updated *after* the callback invocation. Hence
the "onDisconnect" callback is now invoked after the disconnecting
peer is removed from the vector.

* Count peers by looping through the "players" vector.
* Move invocation of "onDisconnect" callback to after peer is deleted.
* Add getPeerCount() calls to example 3 to illustrate use.
This commit is contained in:
rna88 2018-03-13 04:22:22 -07:00
parent bbc9bb3149
commit 85822e682e
2 changed files with 31 additions and 8 deletions

View File

@ -85,9 +85,15 @@ public:
core::stringc message;
message = "Client number ";
message += playerId;
message += " has just connected.";
message += " has just connected. ";
message += netManager->getPeerCount();
message += " peer(s) total.";
packet << message;
netManager->sendOutPacket(packet);
std::cout << "Client number " << playerId << " connected. "
<< netManager->getPeerCount() << " peer(s) total." << std::endl;
}
}
@ -100,10 +106,15 @@ public:
core::stringc message;
message = "Client number ";
message += playerId;
message += " has just left the building.";
message += " has just left the building. ";
message += netManager->getPeerCount();
message += " peer(s) left.";
packet << message;
netManager->sendOutPacket(packet);
std::cout << "Client number " << playerId << " disconnected" << std::endl;
std::cout << "Client number " << playerId << " disconnected. "
<< netManager->getPeerCount() << " peer(s) left." << std::endl;
}
// Handle the packets, as usual.

View File

@ -316,16 +316,18 @@ namespace irr
if(pData)
{
u16 disconnectingPID = pData->playerID;
if(verbose)
std::cout << "irrNetLite: Player number "
<< pData->playerID
<< disconnectingPID
<< " disconnected.\n";
if(pHandler) pHandler->onDisconnect(pData->playerID);
players[pData->playerID] = 0;
players[disconnectingPID] = 0;
delete pData;
event.peer->data = 0;
if(pHandler) pHandler->onDisconnect(disconnectingPID);
}
}
default:
@ -366,7 +368,17 @@ namespace irr
const u32 CNetManager::getPeerCount()
{
return (u32)host->peerCount;
u32 count = 0;
for (u32 i = 1; i < netParams.maxClients; ++i)
{
if (players[i])
{
++count;
}
}
return count;
}
const u16 CNetManager::getPlayerNumber()