Improve connection handling and close behavior