refactored connection handling and managed event mem leaks