====>  html에서 flashVars를 설정한다음 flex에서 parameters 를 통해 로딩하면 됩니다.

원본 글 : http://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_3.html

IN JSP
<html>
<head>
<title>/flex2/code/wrapper/DynamicFlashVarTestWrapper.jsp</title>
<style>
body { margin: 0px;
 overflow:hidden }
</style>
</head>

<%
    String fName = (String) request.getParameter("firstname");
    String mName = (String) request.getParameter("middlename");
    String lName = (String) request.getParameter("lastname");
%>

<body scroll='no'>
<table width='100%' height='100%' cellspacing='0' cellpadding='0'><tr><td valign='top'>

<script>
<h1>Dynamic FlashVarTest Wrapper</h1>
</script>


    <object id='mySwf' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' height='100%' width='100%'>
        <param name='src' value='../assets/FlashVarTest.swf'/>
        <param name='flashVars' value='firstname=<%= fName %>&lastname=<%= lName %>'/>
        <embed name='mySwf' src='../assets/FlashVarTest.swf' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' height='100%' width='100%' flashVars='firstname=<%= fName %>&lastname=<%= lName %>'/>
    </object>

</td></tr></table>
</body>
</html>
or 
 
http://localhost:8100/flex/myApp.swf?myName=Nick&myHometown=San%20Francisco
IN FLEX
<?xml version="1.0"?>
<!-- wrapper/IterateOverApplicationParameters.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
  <mx:Script><![CDATA[
     private function init():void {
        for (var i:String in Application.application.parameters) {
           ta1.text += i + ":" + Application.application.parameters[i] + "\n";
        }
     }
  ]]></mx:Script>
  
  <mx:TextArea id="ta1" width="300" height="200"/>

</mx:Application>

==========================================================================================
기타 추가할 만한 사이트 있으면.... 리플 부탁 드려요 ^_^/

==========================================================================================

1) 움직이는 GIF 로더 컴포넌트 :

활용 : FLEX 어플리케이션에서 움직이는 GIF이미지를 보여줄 수 있음.

주소 : http://code.google.com/p/as3gif/

2) 플렉스 뷰어 컴포넌트 :


활용 : 목록형 이미지를 보여줄때 사용하는 컴포넌트 (IPod 커버 플로우와 유사)

주소 : http://www.quietlyscheming.com/blog/components/tutorial-displayshelf-component/


3) 플렉스 달력 컴포넌트:



활용 : 달력 내부에 다양한 내용을 넣어 스케줄러 등으로 활용 할 수 있음.

주소: http://code.google.com/p/flexcalendar/

4) 반사 컴포넌트 :


활용: 반사 효과

주소 : http://blog.benstucki.net/?id=20

5) 플렉스 단위 테스트 프레임 워크 :

활용 : 플렉스 단위 테스트로 녹화/되감기 가능

주소 : http://code.google.com/p/flexmonkey/

6) 플렉스 테이블 컴포넌트 :


활용 : MS워드와 유사한 형태의 테이블

주소 : http://code.google.com/p/flex-table/

7) 플렉스 라이브러리 프로젝트 :

활용 : 플렉스 오픈소스 라이브러리 프로젝트

주소 : http://code.google.com/p/flexlib/

8) 플렉스 버드아이 프로젝트 :



활용 : 진보화 된 비주얼 라이브러리 (다양한 기능을 포함함.)

주소 : http://code.google.com/p/birdeye/


출처 : http://www.insideria.com/2009/04/51-actionscript-30-and-flex-op.html

51 ActionScript 3.0 and Flex optimization techniques and practices

Author photo
| | Comments (30)
AddThis Social Bookmark Button

A homework assignment I was recently given for a Java programming class involved a competition to see who could create the most optimized implementation of an interface which was provided by the instructor. It was a challenging and very fun assignment that I think the whole class enjoyed. I didn’t win the competition but still came out a winner because of my heightened interest in application optimization and performance tuning that I gained.

I’m personally a pretty big fan of coding standards and have been ribbed by many developers over some of the longer method, variable and class names that I sometimes choose. I've always leaned toward the side of programming that employs standards and frameworks . Rather than spending a ton of time digging around in compiler specs and messing with GC (Garbage Collection) for reasons of performance, tuning and optimization. I was leaving this to the seasoned programmers creating the standards and frameworks I use.

This isn’t to say I’ve never paid attention to performance and I enjoy building slow applications. It’s almost like two different worlds; the optimization world and the standards world. They don’t always agree with each other. There can sometimes be a trade off for performance over readability and organization or vice-versa. This article is meant to stand next to the Flex Best Practices articles that I authored.

While creating my concrete implementation for the homework assignment I discovered a powerful profiling engine in NetBeans. The NetBeans profiling engine helped me understand some of the memory usage and consumption of each property, method call and object instantiation in my program. This profiler in NetBeans is very similar to the one found in Flex Builder. Both are very powerful and very useful. I've been exploring the Flex Profiler in greater detail lately as well and using it to eradicate memory leaks for a real world application I’ve been refactoring to best practices lately.

The Java optimization homework has increased my interest in optimization and profiling for ActionScript 3.0 and Flex development. I've been piecing together ActionScript optimization techniques and practices from around the web for a couple years now. Some of these techniques are in opposition to what the standards dictate but most of software development is this way. You have to learn when to use some techniques and when to leave some out.

Here are 51 ActionScript 3.0 and Flex optimization techniques and practices. I’ve scoured the web for and filtered practices and techniques that can be adopted into your application development process. Use these in conjunction with the Flex Profiler to monitor and optimize and tune the performance of your ActionScript 3.0 and Flex RIAs.

1. Avoid the new operator when creating Arrays

 
var a = [];

NOT:

 
var a = new Array();

2. Arrays are expensive to create, do so conservatively

 
var vanityCollection01 : Array = new Array();
var vanityCollection02 : Array = new Array();
var vanityCollection03 : Array = new Array();
var vanityCollection04 : Array = new Array();

3. Fastest way to copy an array:

 
var copy : Array = sourceArray.concat();

4. Setting values in Arrays is slow

 
employees.push( employee );
employees[2] = employee;

5. Getting values from Arrays is twice as fast as setting

 
var employee : Employee = employees[2];

6. Anonymous objects are faster to create with {} vs. new

 
var o : * = { firstName : "John", lastName : "Smith", age : 45 };
NOT:
var p : Person = new Person();
p.firstName = "John";
p.lastName = "Smith";
p.age = 45;

7. Use static for properties methods that do not require an object instance

 
StringUtils.trim( "text with space at end " );
Class definition:
package
{
public final class StringUtils
{
public static function trim( s : String ) : String
{
var trimmed : String;
// implementation...
return trimmed;
}
}
}

8. Use const for properties that will never change throughout the lifecycle of the application

 
public const APPLICATION_PUBLISHER : String = "Kannopy, Inc.";

9. Use final when no subclasses need to be created of a class

 
public final class StringUtils

10. Use package level variables and functions for generalized functionality which does not require a class or instance of a class

 
createSnapShot( arg );

NOT:

 
someObjectInstance.createSnapShot( arg );

NOT:

 
SomeClass.createSnapShot( arg );
Class definition:
package
{
// imports&#133;;
public function createSnapShot(target:IBitmapDrawable) : Bitmap
{
// implementation&#133;
}
}

11. JIT won’t compile code within constructors (keep them lightweight)

 
package com.seantheflexguy.as3optimization
{
public class MinimalConstructor
{
public function MinimalConstructor()
{
init();
}

}
}

12. Length of method/variable names doesn't matter in ActionScript 3.0 (true in other langs)

 
someCrazyLongMethodNameDoesntReallyImpactPerformanceTooMuch();

13. One line assignments DO NOT buy any performance! It's a Myth! (true in other langs)

 
var i=0; j=10; k=200;

14. No difference in memory usage between an if statement and a switch statement

 
if ( condition )
{
// handle condition
}

IDENTICAL MEMORY USAGE:

 
switch ( condition )
{
case "A":
// logic to handle case A
break;

case "B":
// logic to handle case B
break;
}

15. Rank your if statements in order of comparisons most likely to be true

 
if ( conditionThatHappensAlot )
{
// logic to handle frequently met condition
}
else if ( conditionThatHappensSomtimes )
{
// handle the case that happens occaisonally
}
else
{
// handle the case that doesn&#8217;t happen that often
}

16. AVM promotes int to Number during calculations inside loops

17. Resolve issues of promotion, unknown, or incorrect object types

18. Use uint sparingly, it can be slow

 
var footerHex : uint = 0x00ccff;

19. Use integers for iterations

 
(var i: int = 0; i < n; i++) NOT for (var i: Number = 0; i < n; i++)

20. Cast to int for calculations inside loops (AVM automatically promotes int to Number)

 
for (;i<n2;i++) Vector3D(array[int(i*2)]).x = 2;

NOT:

  
for (;i<n2;i++) Vector3D(array[i*2]).x = 2;

21. Don't use int with decimals

 
var decimal : Number = 14.654;

NOT:

 
var decimal : int = 14.654;

22. Multiply vs. Divide: instead of 5000/1000 use: 5000*0.001

23. Calculate things like floor and round yourself vs. calling Math library

 
package com.seantheflexguy.math
{
public final class MathUtil
{
public static function round( number : Number ) : Number
{
// custom rounding implementation
}
}
}

24. Locally store function values in for and while statements instead of repeatedly accessing them

 
for (..){a*180/Math.PI;}
declare: toRadians = a*180/Math.PI; outside of the loop

25. Avoid calculations and method calls in loops

 
for (var i=0;i< myArray.lengh;i++){ }

NOT:

  
var len : int = myArray.lengh;
for (var i=0;i<len;i++){}

26. Remove event listeners when finished using them

 
removeEventListener( Event.COMPLETE, onComplete );

27. Use delete to free memory

 
delete someObject;

28. Use RegEx for validation, use string methods for searching

 
// postal code validation example using regular expressions
private var regEx:RegExp = /^[A-Z][0-9][A-Z] [0-9][A-Z][0-9]$/i;
private function validatePostal( event : Event ) : void
{
if( regEx.test( zipTextInput.text ) )
{
// handle invalid input case
}
}

// search a string using String methods
var string : String = "Search me";
var searchIndex : int = string.indexOf( "me" );
var search : String = string.substring( searchIndex, searchIndex + 2 );

29. Reuse objects to maintain a “memory plateau” DisplayObjects, URLLoader objects

30. Follow the Flex component model:

 
createChildren();
commitProperties();
updateDisplayList();

31. Only use Datagrids as a last resort (make sure you can’t implement in a regular List first)

32. Avoid Repeaters for scrollable data

33. Avoid the setStyle() method (One of the most expensive calls in the Flex framework)

34. Using too many containers dramatically reduces the performance of your application

 
<mx:Panel>
<mx:VBox>
<mx:HBox>
<mx:Label text="Label 1" />
<mx:VBox>
<mx:Label text="Label 2" />
</mx:VBox>
<mx:HBox>
<mx:Label text="Label 3" />
<mx:VBox>
<mx:Label text="Label 4" />
</mx:VBox>
</mx:HBox>
</mx:HBox>
</mx:VBox>
</mx:Panel>

35. You do not need to always use a container tag as the top-level tag of components Totally valid component, no top level container needed:

 
<mx:Image xmlns:mx="http://www.adobe.com/2006/mxml"
source="avatar.jpg" width="200" height="200" />

36. Remove unnecessary container wrappers to reduce container nesting

37. Avoid: The VBox container inside an tag, (eliminates redundancy)

 
<mx:Panel>
<mx:Label text="Label 1" />
<mx:Label text="Label 2" />
</mx:Panel>
NOT:
<mx:Panel>
<mx:VBox>
<mx:Label text="Label 1" />
<mx:Label text="Label 2" />
</mx:VBox>
</mx:Panel>

38. Avoid: VBox container inside an tag, (eliminates redundancy)

 
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml>
<mx:Label text="Label 1" />
<mx:Label text="Label 2" />
</mx:Application>

NOT:

 
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml>
<mx:VBox>
<mx:Label text="Label 1" />
<mx:Label text="Label 2" />
</mx:VBox>
</mx:Application>

39. Set the recycleChildren property to true to improve a Repeater object's performance (re-uses previously created children instead of creating new ones)

 
<mx:Script>
<![CDATA[
[Bindable]
public var repeaterData : Array = ["data 1", "data 2"];
]]>
</mx:Script>

<mx:Repeater id="repeater" dataProvider="{repeaterData}">
<mx:Label text="data item: {repeater.currentItem}"/>
</mx:Repeater>

40. Keep framerate set at 60 fps or lower

 
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml
frameRate="45">
</mx:Application>

41. Avoid multiple display manipulations per frame

42. Code against ENTER_FRAME events instead of Timer events

 
public function onEnterFrame( event : Event ) : void
{
}
private function init() : void
{
addEventListener( Event.ENTER_FRAME, onEnterFrame );
}

NOT:

 
public function onTimerTick( event : Event ) : void
{
}
private function init() : void
{
var timer : Timer = new Timer();
timer.start();
timer.addEventListener( TimerEvent.TIMER, onTimerTick );
}

43. To defer object creation over multiple frames use:

 
<mx:Container creationPolicy=&#8221;queued&#8221;/>

44. Alpha = 0 is not the same as visible = false (Objects marked invisible are passed over)

 
loginButton.visible = false;

NOT:

 
loginButton.alpha = 0;

45. Faster to perform operations locally than it is to call a function in the same class Even slower to call a function from a different class (This is referred to as “code inlining”.)

46. When executing a function it’s more expensive if you call other functions from within it

 
private function udpateUserRecord()
{
update( user.firstName + user.lastName );
}

NOT:

 
private function updateUserRecord() {
update( concatName() );
}
private function concatName() : String
{
return user.firstName + user.lastName;
}

47. Arguments in functions are slower than a reference to an objects variables

 
package com.seantheflexguy.as3optimization
{
public class DemoClassMemberVariables
{
// set the properties on class instances
public var userName : String;
// etc...
public function DemoClassMemberVariables()
{
}
private function login() : void
{
// login implementation logic
userName = creds.getUserName();
// etc...
}
}
}

NOT:

 
package com.seantheflexguy.as3optimization
{
public class DemoClassArguments
{
public function DemoClassArguments()
{
}
private function login( creds : Authentication ) : void
{
// login implementation logic
userName = creds.getUserName();
// etc...
}
}
}

48. Faster to use "as" vs. casting

 
var u : User = event.results.users.user as User;

NOT:

 
var u : User = User(event.results.users.user);

49. Use custom object types vs new Object();

 
var v3D : Vector3D = new Vector3D();
v3D.x = 100;
v3D.y = 450;
v3D.z = 500;

NOT:

 
var v3DObject : Object = new Object();
v3DObject.x = 100;
v3DObject.y = 450;
v3DObject.z = 500;

50. Use casting to inform the Flash player what kind of objects are inside an Array

 
for (i=0;i<n;i++)
{
Vector3D( array[i] ).x = 2;
}

NOT:

 
for (i=0;i<n;i++)
{
array[i].x = 2;
}

51. Check for null instead of using try...catch blocks

 
if ( o != null )
{
o.method();
}

NOT:

 
try
{
o.method();
}
catch ( error )
{
trace( error );
}

References:

Sean Christmann: Optimizing Adobe AIR for Code Execution, Memory, and Rendering
http://www.craftymind.com/2008/11/20/max-2008-session-material/

Dennis Ippel: Some ActionScript 3.0 Optimizations
http://www.rozengain.com/blog/2007/05/01/some-actionscript-30-optimizations/

Shane McCartney: Tips on how to write efficient AS3
http://www.lostinactionscript.com/blog/index.php/2008/09/28/tips-on-how-to-write-efficient-as3/

Flex Application Performance: Tips and Techniques for Improving Client Application Performance
http://www.adobe.com/devnet/flex/articles/client_perf.html

Stephen Calender: ActionScript 3.0 Benchmarking
http://www.stephencalenderblog.com/?p=7

Grant Skinner: Types in AS3: ints not so fast, uints slow!
http://www.gskinner.com/blog/archives/2006/06/types_in_as3_in.html

Grant Skinner: Resource management strategies in Flash Player 9
http://www.adobe.com/devnet/flashplayer/articles/resource_management.html

Gary Grossman: ActionScript 3.0 and AVM2 Performance Tuning
http://www.onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf

Fastest way to copy an array
http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/

Andre Michelle: AS3 optimations & suggestions
http://blog.andre-michelle.com/2005/as3-optimations-suggestions/

Package-level function closures in ActionScript
http://www.ericfeminella.com/blog/2008/05/06/package-level-function-closures-in-actionscript/

ActionScript 3 optimization techniques
http://blog.joa-ebert.com/2008/04/26/actionscript-3-optimization-techniques/

AS3 Performance Tester
http://businessintelligence.me/projects/performance_tester/performanceTester.html

서버 : 자바 -> 받는 것만 됨
클라 : 플렉스 -> 받는거 보내는거 다됨

기억이 가물 가물해서 자바는 소스가 좀 ;; 크라이언트 소켓 테스트 하는데는 문제 없으므로 테스트용으로 사용하세요. -_-;

 import java.net.*;

import java.io.*;


//테스트용임 .....  


public class TestServer extends Thread{
    private BufferedReader recv_msg = null;
    private Socket soc = null;
    
    public TestServer(){
        ServerSocket server = null;
        try {
            server = new ServerSocket (300);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        System.out.println ("Server Running");
        
        
        
        while (true) {

            try{
                soc = server.accept();
                System.out.println(soc.toString());
                recv_msg = new BufferedReader(new InputStreamReader(soc.getInputStream()));                
                recv_message rm = new recv_message();
                rm.start();                
            }catch (Exception e) {
                e.printStackTrace();
            }            
        }
        
    }

    public class recv_message extends Thread{
        public void run(){
            while(true){
                if(soc==null) return;
                try {
                    String msg = recv_msg.readLine().trim();
                    System.out.println("size : ["+msg.length()+"]"+msg.trim());
                    if(msg.equals("exit")){
                        System.out.println("종료");
                        soc.close();
                        soc=null;                                        
                    }
                } catch (Exception e) {                    
                    e.printStackTrace();
                }



                try{
                    Thread.sleep(200);
                }catch(Exception e){
                    
                }
                
            }
        }
    }
    
    
    public static void main (String args[]) throws Exception{
        new TestServer();
    }
}


 <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            import mx.formatters.SwitchSymbolFormatter;
            import mx.controls.Alert;      
            import flash.net.Socket;
           
            public var m_socket:Socket = new Socket();
           
            public function connect():void{
                if(m_socket.connected == false){
                    trace("연결 : 연결시도");
                    m_socket.connect("localhost", 300);
                    m_socket.addEventListener(ProgressEvent.SOCKET_DATA,rcvHandler);
                    m_socket.addEventListener(IOErrorEvent.IO_ERROR,ioHandler);
                }else{
                    trace("연결 : 이미 연결되어 있음.");
                }
            }
           
            public function close():void{
                if(m_socket.connected == true){
                    trace("종료 : 연결을 종료 합니다.");
                    m_socket.writeUTFBytes("exit\n");
                    m_socket.flush();
                    m_socket.close();
                }else{
                    trace("종료 : 연결되어 있지 않음.");
                }
            }
           
            public function sendData():void
            {
                if(m_socket.connected == true)
                {
                    var bytes:ByteArray = new ByteArray();
                    bytes.writeUTFBytes(txtData.text+"\n");
                    bytes.position = 0;
                    
                    m_socket.writeBytes(bytes,0,bytes.length);
                    trace("메시지 : "+txtData.text);
                    m_socket.flush();
//                    m_socket.writeUTFBytes( txtData.text);
                    
                    txtData.text = "";
                }
                else
                {
                    Alert.show("연결되지 않았음");
                }
            }
            
            private function sndMsg(evt:KeyboardEvent):void{
                switch(evt.keyCode){
                    case Keyboard.ENTER:
                        sendData();
                    break;
                }
            }
            
            private function ioHandler(evt:IOErrorEvent):void{
                trace("io error");
            }
            
            private function rcvHandler(evt:ProgressEvent):void{
                trace("socketDataHandler: " + evt);
                readResponse();
            }
            
            private function readResponse():void{
                var str:String = m_socket.readUTFBytes(m_socket.bytesAvailable);
                txtRead.text += str;
            }
           
        ]]>
    </mx:Script>
    <mx:VBox width="237" height="138">
        <mx:HBox>
            <mx:Button label="connect" click="connect()"/>           
            <mx:Button label="close" click="close()" />
        </mx:HBox>

        <mx:HBox>
            <mx:TextInput id="txtData" keyDown="sndMsg(event)"/>
            <mx:Button label="send" click="sendData()"/>       
        </mx:HBox>       
        <mx:TextArea width="100%" height="100%" id="txtRead"/>
    </mx:VBox>
</mx:Application>


Flash 와 App간 통신 방법 3가지를 소개했었는데, AS3로 넘어오면서 watch명령이 없어져서 기존에 사용하던 fscommand/setVariable 방법을 사용할수 없어졌습니다. watch 명령이 아주 비효율적이라 아예 없앴다고 합니다. LocalConnection 방법은 편법성으로 사용자들이 알아낸 방법이므로, ExternalInterface로 Flash와 APP간 통신을 구현했습니다.


1. Application에서 Flash 함수 호출

Actionscript3 소스:
ExternalInterface.addCallback("callFromApp", function(a, b) { return "ok:"+a+","+b; });


C++ 소스:
string invXml = ExternalInterface::MakeInvokeXml("callFromApp", arg1, arg2);
string ret = ExternalInterface::ParseResultXml(m_cFlash.CallFunction(invXml.c_str()).GetBuffer(0));


2. Flash에서 Application 호출

Actionscript3 소스:
ExternalInterface.call("testfunc", "hello", 1, true, 1==2, 1.1);

C++ 소스:
void CFlashTestApp::OnFlashCallShockwaveflash1(LPCTSTR request)
{
   string cmd;
   vector<string> args;

   if (ExternalInterface::ParseInvokeXml(request, cmd, args)) {
      // 함수콜 처리하기~
   }
}


--
Flash와 APP간 통신은 모두 XML을 통해서 이루어집니다.
1. 어플에서 XML을 만들고 파싱해야합니다.
2. 외부 XML 파서를 쓸수 있지만, 사용하는 XML이 복잡하지 않아서 자체 XML 파서를 만들었습니다.
3. Flash에서는 type이 있지만, C++에서는 모두 string으로 받도록 했습니다. C++에서 보낼때도 모두String인자로 보냅니다. 어차피 XML이 문자열로 되어 있으므로, string으로 처리해도 퍼포먼스에 크게 영향이 없을것으로생각되고, Variant를 C++에서 구현하는것은 복잡하고 짜증나는 작업이죠.
4. ActionScript에서 전달한 인자 중 복잡한 자료구조는 파싱하지 못하고,   String, Number,Boolean등과 1차 Array만 파싱하도록 했습니다. C++에서는 인자 받은걸 순서대로 vector에 넣어서 처리를단순화했습니다. Array안에 Array등을 처리하려면 C++에서도 복잡한 자료구조가 필요하고, 그러면 함수처리하는 부분도복잡해질듯해서 단순화했습니다.
5. STL string을 이용해서 파싱했습니다.


XML 파싱 함수들 입니다.

string peek_element(const string &xml);
xml에 포함된 첫 element를 가져옵니다. peek = 엿보기?

bool parse_element(const string &name, string &xml, string &attrs, string &inner);

xml에 포함된 첫 element를 파싱해서 attribute부분과 innerXml부분으로 나누어줍니다. xml에서는 파싱한 부분을 제거합니다.
   name = a
   xml = <a attr="haha">aab</a><b>zzz</b>
이런식으로 호출되면...
   attrs = attr="haha"
   inner = aab
   xml = <b>zzz</b>
이런식으로 값이 바뀝니다.

bool parse_attributes(const string &attrs, StringMap &attrMap);
<element attr1="val1" attr2="val2">
위에 같은 xml attributes을 파싱해서 attrMap에 insert합니다. "attr1"→"val1", "attr1"→"val2"

string xml_encode(const string &x); // <, &, > → &lt;, &amp;, &gt;

string xml_decode(const string &x);
// &lt;, &amp;, &gt; → <, &, >

Flash -> Application XML 예제
ExternalInterface.call("testfunc", "hello", 1, true, 1==2, 1.1);

<invoke name="testfunc" returntype="xml">
   <arguments>
       <string>hello</string>
       <number>1</number>
       <true/>
       <false/>
       <number>1.1</number>
   </arguments>
</invoke>


Flash -> Application XML 파싱 소스:
// external interface 파싱
bool parse_arg(string &xml, string &val)
{
   string attrs, i;
   if (parse_element("string", xml, attrs, i)) {
       val = i;
   } else if (parse_element("number", xml, attrs, i)) {
       val = i;
   } else if (parse_element("true", xml, attrs, i)) {
       val = "true";
   } else if (parse_element("false", xml, attrs, i)) {
       val = "false";
   } else if (parse_element("boolean", xml, attrs, i)) {
       val = i;
   } else {
       return false;
   }
   return true;
}

void parse_args(string &xml, vector<string> &args)
{
   string val;
   while (1) {
       if (parse_arg(xml, val)) {
           args.push_back(val);
       } else {
           break;
       }
   }
}

bool ParseInvokeXml(const string &_xml, string &cmd, vector<string> &args)
{
   string xml=_xml;
   string attrs;
   string innerXml;

   parse_element("invoke", xml, attrs, innerXml);

   StringMap attrMap;
   parse_attributes(attrs, attrMap);

   StringMap::const_iterator f = attrMap.find("name");

   if (f != attrMap.end()) {
       cmd = f->second;
       string elm = peek_element(innerXml);
       string p, i;
       if (parse_element("arguments", innerXml, attrs, i)) {
           innerXml = i;
           if (parse_element("array", innerXml, attrs, i)) {
               innerXml = i;
               while (parse_element("property", innerXml, attrs, i)) {
                   parse_args(i, args);
               }
           } else {
               parse_args(innerXml, args);
           }
       }
   }
   return true;
}

+ Recent posts