Refactoring to avoid socket overwriting