Sending compressed bytes between as3 and PHP

Not sure if someone else is doing this or have done this before, but I kinda stumbled upon sending compressed string data to PHP and back. In theory, the data transfer and bandwidth being used is a lot smaller, since the data is compressed through the tubes and inflated when received in actionscript and php. I have written some example codes below on how to do this approach.

Example Flash Code

import flash.net.*;
var longstring = “Replace this with a really long text to see a better compression length comparison”;
var datarequest:URLRequest = new URLRequest();
datarequest.url = “http://www.badongers.com/compressed.php”;
datarequest.contentType = “application/octet-stream”; //set content type as octet-stream
datarequest.method = “POST”;

var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(longstring); //write string to ByteArray
trace(”before compression ” + byteData.length);
byteData.compress();
trace(”after compression “+ byteData.length);
datarequest.data = byteData; //send compressed byte

var dataloader:URLLoader = new URLLoader()
dataloader.load(datarequest);
//set data format as binary
dataloader.dataFormat = URLLoaderDataFormat.BINARY;
dataloader.addEventListener(Event.COMPLETE, resultHandler);
function resultHandler(evt:Event):void{
var byteReceived:ByteArray = dataloader.data;
trace(”compressed ” + byteReceived.length);
byteReceived.uncompress();
trace(”uncompressed ” + byteReceived.length);
trace(byteReceived.toString());
}

Example PHP receive and reply code

< ?php
$postedData = file_get_contents( ‘php://input’ );
//uncompress this data
//$uncompressedPostedData = gzuncompress($postedData);
$longreply = “Replace this with a really long text to see a better compression length comparison”;
echo gzcompress($longreply, 9);
?>

This is a lot useful if you are sending XML between the 2, making the information a lot more readable when inflated on both sides. This is also not limited to string, since it is using binary data transfer.


About this entry