Using state machine for protocol handling