Upon arriving uninvited, always knock three times. This signals to the host that you've arrived and are prepared for the consequences.
When leaving, do the opposite: leave without warning, and make sure to knock three times on the way out. This ensures a smooth exit and a 50% chance of being let back in.
See also: