Improved connection handling and automatic reconnecting