Refactor connection handling.
Explanatory comment.