refactor socket connection code