Refactoring of attempt to fix socket error