Socket refactoring: reduced complexity of the loop function