I have been experiencing a bug when receiving packets.
I am using a blocking socket.
A few lines into the function ...
Socket::Status SocketTCP::Receive(Packet& packet)
if (myPendingPacketSize < 0)
{
Socket::Status status = Receive(reinterpret_cast<char*>(&packetSize), sizeof(packetSize), received);
if (status != Socket::Done)
return status;
packetSize = ntohl(packetSize);
}
There is no check for if (sizeof(packetSize) == received)
sizeof(packetSize) is only 4 bytes so almost always all 4 bytes will be received on the first return of Receive.
But not ALWAYS. I have debugged the "received" value in this function to rarely come out 1,2, or 3 which causes packetSize to be read incorrectly, reading into the middle of a packet, and messing up all further received packets on that socket.
Something like the following needs to be done when receiving the header of the packet. ( It's similar to what is being done when receiving the packet's data. It was just assumed 4 bytes is always read first try for the header. )
std::size_t Received = 0;
while (Received < sizeof(PacketSize))
{
std::size_t r;
Socket::Status Status = Receive(reinterpret_cast<char*>(&PacketSize)+Received, sizeof(PacketSize)-Received, r);
if (Status != Socket::Done)
return Status;
Received += r;
}
PacketSize = ntohl(PacketSize);
When using this modification all of my packets are received correctly 100% of the time. It could be dependent on the OS for who would experience the problem and who wouldn't.