Refactoring to avoid unwanted socket closing