Refactor socket code