Handle disconnection and shutdown properly