refactored socket handler