Stream handling and error handling improved

I have added some helpful log messages when errors occur and corrected the stream and connection handling.