refactor connection establishment

reduces duplicated code, and makes it easier for future changes
to connection establishment because it's all in one place now