Refactored receivePacket function