refactoring socket code for reusability