Refactored socket logic