在AIR应用中利用ZLIB压缩数据
By Minidxer | September 6, 2008
对于一些传输数据比较庞大的应用来说,对数据进行压缩是比较通用的做法。AMF3格式可以有很好的压缩比率,不过这个算法有一个致命的问题:对于那些基本上没有相同字符串或者很少相同字符串的数据,AMF3的压缩的比例是让人失望的。所以AMF3适用的范围有很大的局限性。ZLIB算法则没有这样的问题(当然也可以在数据压缩里找到其他的,不过整合在AIR中使用可能就比较费力气了)。下面分别是AIR中所需要的ActionScript,Java代码以及remoting-config.mxl。
ActionScript代码:
- <mx:RemoteObject id="SendData" destination="SendData"/>
- <mx:Script>
- <![CDATA[
- import flash.utils.*;
- private function send():void{
- var testString:String =
- "Test - Alice in Wonderland";
- var bytes:ByteArray = new ByteArray();
- bytes.writeUTF((testString));
- bytes.compress(CompressionAlgorithm.ZLIB);
- SendData.sendData(bytes);
- }
- ]]>
- </mx:Script>
Java代码:
- public void sendData(byte[] bytes) throws Exception{
- Inflater decompresser = new Inflater();
- decompresser.setInput(bytes, 0, bytes.length);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
- byte[] result = new byte[1024];
- while(!decompresser.finished()){
- int resultLength = decompresser.inflate(result);
- bos.write(result,0,resultLength);
- }
- decompresser.end();
- DataInputStream ddd = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
- try{
- while(true){
- System.out.println(ddd.readUTF());
- }
- }catch(EOFException e){
- }
- }
最后是remoting-config.mxl:
- <destination id="SendData">
- <channels>
- <channel ref="my-amf"/>
- </channels>
- <properties>
- <source>
- test.SendData
- </source>
- <scope>application</scope>
- </properties>
- <adapter ref="java-object" />
- </destination>
更加具体的说明,我们可以看这里:
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=10643