fixed connection state and error handling bugs