Refactoring socket code to be more clear