Refactoring: tidied up main connection event handler.