Flex/flash/ajax using compression to solve the problem of asynchronous transmission optimization of large data quantity

Source: Internet
Author: User
Tags base64

This article data is wrong, cause the compression effect conclusion seriously deviate from the fact, the correct situation is, that is, use deflate compression, and gzip compression effect is very similar, because they are originally from Huffman coding in the branch out ... If you also want to understand the next transmission optimization, you can search the next messagepack may be able to help you ~

First, think about what data we're transmitting asynchronously, picture or text? If is the picture video class, sorry, the following content does not need to look, can not help you. What we're talking about here is the transmission of text, the case of text (I believe that 99% of the asynchronous process is all about this).

OK, let's talk about the principle first. Why the picture and video class is not optimized, the reason is that these things are already 2 into the system, and we usually look at the text is 10 into the system. If we before transmission, the text into 2 compression, after the client received data and then do 2 into the 10 into the decompression, can greatly reduce the amount of asynchronous transmission of data. My test results Here are 673KB of data, after 2 compression, and compatibility processing, the size of 18KB, a full reduction of 99.97% of the data transfer volume. Can say, greatly reduce the customer load data time, customer experience on several levels.


A simple conversion to the binary is not a D, to the binary compression to achieve the Super invincible compression effect. Here occasionally intoxicated I was using PHP as a service-side, the client is using Flex. Fortunately, the powerful PHP has put this compression algorithm-deflate built into PHP, in PHP can be used directly gzdeflate compression, gzinflate for decompression.

What is deflate?

Deflate is a lossless data compression algorithm using LZ77 algorithm and Huffman Coding (Huffman coding). It was originally defined by Phil Katz for his second edition of the PKZIP Archiving tool, which was later defined in the RFC 1951 specification.

It is generally accepted that deflate is not subject to any patent and that this format is applied in gzip compressed files and PNG image files in addition to being applied in the ZIP file format, prior to the expiration of the patent associated with the LZW (GIF file format).

Deflate compression and decompression of the source code can be found in the free, Universal compression library zlib.

This is an open source algorithm, there should be any version of it, other languages have this built-in calculation. The client word, I use the flex also has this algorithm package, as long as import flash.utils.ByteArray; You can use the ByteArray object to invoke the inflate () function for decompression.

I believe that see this article are more than the program ape, said no more useless, as well as directly affixed to the source code ... Haha, finally attached source code. Of course, just a simple demo, convenient for everyone to understand it. First of all, this demo is analog Flex call PHP interface, PHP analog compression return a lot of data, flex transfer to the data after decompression processing, and then draw (K-line chart).


)。

The code is as follows Copy Code
<?php
$file = ' c:/test.txt ';
$content = file_get_contents ($file);
File_put_contents (' C:/1.txt ', Base64_encode (Gzdeflate ($content, 6));
Header ("Content-length:". strlen (Base64_encode (Gzdeflate ($content)));
Echo Base64_encode (Gzdeflate ($content));

?>

The following is a flex code that simulates stock chart and requires a large amount of data to be invoked.

The code is as follows Copy Code

<?xml version= "1.0″encoding=" utf-8″?>

<s:application xmlns:fx= "Http://ns.adobe.com/mxml/2009″

Xmlns:s= "Library://ns.adobe.com/flex/spark"

xmlns:mx= "Library://ns.adobe.com/flex/mx" minwidth= "955″minheight=" 600″creationcomplete= "init ()" >

<fx:Declarations>

<mx:httpservice id= "SRV" resultformat= "text" useproxy= "false" result= "Resultdatas (event)"/>

<!–k Line chart rose down 2 kinds of styles –>

<mx:solidcolor id= "Up" color= "Red" alpha= ".8″/>"

<mx:solidcolor id= "Down" color= "green" alpha= ".8″/>

<!– some lines –>

<mx:solidcolorstroke id= "line_ma5″color=" #ff8040 ″weight= "0.5″alpha=" 1″/>

<mx:solidcolorstroke id= "line_ma10″color=" #60A2FF "weight=" 0.5″/>

<mx:solidcolorstroke id= "line_ma20″color=" #ff00ff "weight=" 0.5″/>

<mx:solidcolorstroke id= "line_ma30″color=" #008000 ″weight= "0.5″/>

<!– places non-visual elements (such as services, value objects) here –>

</fx:Declarations>

<fx:Script>

<! [cdata[

/*

* Deflate.mxml

* Author: Occasionally intoxicated blog:www.stutostu.com

* Function: Simulate stock chart, invoke large amount of data to PHP interface

*/

Import Flash.utils.ByteArray;

Import mx.collections.ArrayCollection;

Import Mx.controls.Alert;

Import Mx.controls.Label;

Import mx.rpc.events.ResultEvent;

Import Mx.utils.Base64Decoder;

Import Spark.components.TextArea;

private Var str:string;

[bindable]

private Var _mydata:arraycollection;

private Var big:arraycollection;

private Var page:int=1;

private Var Allpage:int;

private var start:int = 0;

Private Function init (): void{

This.systemManager.stage.addEventListener (Keyboardevent.key_down, _keydownhandler);

Srv.url = "http://localhost/test.php";

Srv.send ();

}

Private Function Resultdatas (event:resultevent): void{

str = event.result.toString ();

var base64:base64decoder = new Base64decoder ();

Base64.decode (str);

var byte:bytearray = new ByteArray ();

byte = Base64.tobytearray ();

Byte.inflate ();

var result:string = byte.tostring ();

var words:array=result.split (';');

var subwords:array=[];

Allpage = words.length-1;

var max:number=1;

var min:number=100000;

Big = new ArrayCollection ();

Alert.show ("Ooxx");

for (var i:int = 0;i <= allpage;i++)

{

Subwords=words[i].split (', ');

Subwords[0] = Subwords[0].substr (0,10);

Big.additem ({"Date": subwords[0], "Open": Number (subwords[1)), "High": Number (subwords[2)),

' Low ': Number (subwords[3]), "Close": Number (Subwords[4]), "Vol.": Number (subwords[5)),

"Amount": subwords[6], "vma5″:subwords[7", "vma10″:subwords[8", "vma20″:subwords[9",

"Ma5″:subwords[10]," ma10″:subwords[11], "ma20″:subwords[12", "ma30″:subwords[13",

"K": subwords[14], "D": subwords[15], "J": subwords[16], "Diff": subwords[17],

"Dea": subwords[18], "MACD": subwords[19]};

}

Extrude ();

}

Public Function Extrude (): void{

Page <= 0? page = 1: ";

var end:int = page*30;

_mydata = new ArrayCollection ();

for (Var i:int=0;i<=end;i++)

{

_mydata.additem ({"Date": big[i][' Date '), "open": big[i][' open ', "high": big[i][' high '],

"Low": big[i][' low '], "close": big[i][' Close ', "Vol": Big[i][' Vol '],

"Amount": big[i][' Amount '});

}

}

protected function _keydownhandler (event:keyboardevent): void{

Switch (Event.keycode)

{

Case 38:

page–;

Extrude ();

Break

Case 40:

page++;

Extrude ();

Break

}

}

]]>

</fx:Script>

<mx:candlestickchart id= "Candlestickchart" width= "100%" height= "70%" #040404 chromecolor=

Color= "#FFFFFF" dataprovider= "{_mydata}"

Paddingleft= "2″showdatatips=" false "

Textalign= "Right" >

<mx:verticalAxis>

<mx:linearaxis id= "Vaxis" baseatzero= "false"/>

</mx:verticalAxis>

<mx:verticalAxisRenderers>

<mx:axisrenderer axis= "{vaxis}" placement= left "labelgap=" 0″>

<mx:axisStroke>

<mx:solidcolorstroke color= "#CCCCCC" weight= "1″alpha=" 0.8″/>

</mx:axisStroke>

</mx:AxisRenderer>

</mx:verticalAxisRenderers>

<mx:horizontalAxis>

<mx:categoryaxis id= "Haxis" categoryfield= "Date"/>

</mx:horizontalAxis>

<mx:horizontalAxisRenderers>

<mx:axisrenderer axis= "{haxis}" candroplabels= "true" >

<mx:axisStroke>

<mx:solidcolorstroke color= "#bbccdd" weight= "1″alpha=" 0.8″/>

</mx:axisStroke>

</mx:AxisRenderer>

</mx:horizontalAxisRenderers>

<mx:series>

<mx:candlestickseries id= "Main_line"

Openfield= "Open"

Highfield= "High"

lowfield= "Low"

Closefield= "Close"

Fill= "{Up}"

Declinefill= "{Down}"

/>

<mx:lineseries yfield= "ma5″linestroke=" {line_ma5} "/>

<mx:lineseries yfield= "ma10″linestroke=" {line_ma10} "/>

<mx:lineseries yfield= "ma20″linestroke=" {line_ma20} "/>

<mx:lineseries yfield= "ma30″linestroke=" {line_ma30} "/>

</mx:series>

</mx:CandlestickChart>

</s:Application>


Haha, very simple demo, hope to help you understand what I am saying ... If I can help you, please leave a message to support me oh ... You can also share this article with your friends by sharing the button ...

Finally attached test data, that is, PHP called test.txt this data altogether more than 600 KB, test it, you will find that compression, really very cow ...

Test.txt (right-click Save As Can)

—————— –bug Repair--Update time: 2012/4/12 10:29 ———————-

There was a problem with Chrome's return of compressed data during a general compatibility test. It is found that the reason is transfer-encoding:chunked. The Chrome browser uses a strict chunked protocol and does not receive an explicit chunked terminator to cause an error. So as long as the output data in PHP, with the header set up Content-length told the browser, the return of the data length, you can avoid this happening.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.