Refactor and allow better stopping of server.