Add connect event, fix memory leaks