Integrate the code in the packet reading function, instead of inserting sleeps in many places. This is simpler to follow and should work better.