Refactor connection handler