LocalConnecton的性能问题[慎用LocalConnection]
LocalConnection可以实现在两个SWF文件的通信,不过存在延时问题,延时的时间跟发送的数据量有关,如果只是做普通的通信到没有什么所谓,如果是利用LocalConnection做实时的数据推送就会出现很严重的延时问题。频繁进行send操作,一方面会使内存不断上升,并且消息的接收方的速度与消息的发生速度不同步,停止发送信息之后仍然可以接收到数据。
下面通过一个简单的例子看LocalConnection的性能问题:
发送方SWF,定时器每500毫秒发送一次数据。
1: <?xml version="1.0" encoding="utf-8"?>
2: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="Init()">
3: <mx:Script>
4: <![CDATA[
5: import flash.net.LocalConnection;
6:
7: private var conn:LocalConnection;
8: private var SendNo:uint=0;
9: private var SendTimer:Timer;
10: public function Init():void{
11: conn=new LocalConnection();
12: conn.addEventListener(StatusEvent.STATUS, onStatus);
13:
14: SendTimer=new Timer(500);
15: SendTimer.addEventListener(TimerEvent.TIMER,handlerSend);
16: SendTimer.start();
17: }
18:
19: public function handlerSend(event:TimerEvent):void
20: {
21: SendNo++;
22: var data:Array=new Array();
23: for(var i:uint=0;i<20000;i++)
24: {
25: data[i]="a";
26: }
27: trace(new Date()+" SendNo:",SendNo);
28: conn.send("LocalConnectionTest", "testHandler",data.join(""));
29: txtMessage.text=new Date()+",SendNo:"+SendNo+ "\n"+txtMessage.text;
30: }
31:
32:
33:
34: private function onStatus(event:StatusEvent):void {
35: switch (event.level) {
36: case "status":
37: trace("send() OK.");
38: break;
39: case "error":
40: trace("send() Fault");
41: break;
42: }
43: }
44:
45: ]]>
46:
47: </mx:Script>
48: <mx:Canvas width="400" height="300" borderColor="#333333" borderStyle="solid" borderThickness="1">
49: <mx:TextInput id="txtMessage" width="100%" height="100%"/>
50: </mx:Canvas>
51: </mx:Application>
52:
接收方SWF,只做简单的字符拼接:
1: <?xml version="1.0" encoding="utf-8"?>
2: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="Init()">
3: <mx:Script>
4: <![CDATA[
5: import flash.net.LocalConnection;
6:
7: private var conn:LocalConnection;
8: private var receiveNo:uint=0;
9: public function Init():void{
10: conn=new LocalConnection();
11: conn.client=this;
12: try{
13: conn.connect("LocalConnectionTest");
14: }
15: catch(error:ArgumentError){
16: trace("ArgumentError");
17: }
18: }
19:
20: public function testHandler(msg:String):void{
21: receiveNo++;
22: lbInfo.text+=msg+"\n";
23: trace(msg);
24: trace(new Date()+",receiveNo:"+receiveNo);
25: txtMessage.text=new Date()+",receiveNo:"+receiveNo+ "\n"+txtMessage.text;
26: }
27: ]]>
28: </mx:Script>
29:
30: <mx:Label id="lbInfo" visible="false"/>
31: <mx:Canvas width="400" height="300" borderColor="#333333" borderStyle="solid" borderThickness="1">
32: <mx:TextInput id="txtMessage" width="100%" height="100%"/>
33: </mx:Canvas>
34: </mx:Application>
35:
运行结果: