在AIR应用中利用ZLIB压缩数据

By Minidxer | September 6, 2008

对于一些传输数据比较庞大的应用来说,对数据进行压缩是比较通用的做法。AMF3格式可以有很好的压缩比率,不过这个算法有一个致命的问题:对于那些基本上没有相同字符串或者很少相同字符串的数据,AMF3的压缩的比例是让人失望的。所以AMF3适用的范围有很大的局限性。ZLIB算法则没有这样的问题(当然也可以在数据压缩里找到其他的,不过整合在AIR中使用可能就比较费力气了)。下面分别是AIR中所需要的ActionScript,Java代码以及remoting-config.mxl。


ActionScript代码:

  1. <mx:RemoteObject id="SendData" destination="SendData"/>  
  2. <mx:Script>
  3.     <![CDATA[          
  4.         import flash.utils.*;          
  5.         private function send():void{
  6.              var testString:String =
  7.                                "Test - Alice in Wonderland";
  8.              var bytes:ByteArray = new ByteArray();
  9.               bytes.writeUTF((testString));                        
  10.              bytes.compress(CompressionAlgorithm.ZLIB);                                 
  11.              SendData.sendData(bytes);
  12.         }          
  13.     ]]>
  14. </mx:Script>

Java代码:

  1. public void sendData(byte[] bytes) throws Exception{      
  2.     Inflater decompresser = new Inflater();
  3.     decompresser.setInput(bytes, 0, bytes.length);
  4.     ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
  5.     byte[] result = new byte[1024];
  6.     while(!decompresser.finished()){
  7.         int resultLength = decompresser.inflate(result);
  8.         bos.write(result,0,resultLength);  
  9.     }      
  10.     decompresser.end();                      
  11.     DataInputStream ddd = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
  12.     try{
  13.         while(true){
  14.             System.out.println(ddd.readUTF());
  15.         }
  16.     }catch(EOFException e){          
  17.     }     
  18. }

最后是remoting-config.mxl:

  1. <destination id="SendData">
  2.     <channels>
  3.         <channel ref="my-amf"/>
  4.     </channels>
  5.     <properties>
  6.         <source>
  7.             test.SendData              
  8.         </source>
  9.         <scope>application</scope>
  10.     </properties>
  11.     <adapter ref="java-object" />
  12. </destination>

更加具体的说明,我们可以看这里:

http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=10643

Topics: Adobe其他 | No Comments » | Tags: , , ,

Search Posts