Refactor the code, add statemachine to simplify both server and client logic.