refactored socket function