Sunday, September 11, 2011

FLASH REMOTING WITH AS3

Using remoting in AS3 is actually quite simple. Remoting calls are now made directly through NetConnection, so there's no need for Remoting classes or components, everything you need is readily available. Here is a quick example.

This is a wrapper class for NetConnection that makes sure we are using the right AMF encoding. The default is AMF3, which is not supported on AMFPHP versions lower than 2.0. So, we use AMF0 instead. Save this class as "RemotingService.as".

/*************************** FLASH CODE **************************************/
package
{
    import flash.net.NetConnection;
    import flash.net.ObjectEncoding;

    public class RemotingService extends NetConnection
    {       
        function RemotingService(url:String)
        {
            // Set AMF version for AMFPHP
            objectEncoding = ObjectEncoding.AMF0;
            // Connect to gateway
            connect(url);
        }
    }
}
/*****************************************************************/

The next class is just a test that uses the previous class to make a call. Save it as "RemotingTest.as".

/**************************** FLASH CODE *************************************/
package
{
    import flash.net.Responder;

    public class RemotingTest
    {
        private var rs:RemotingService;

        function RemotingTest()
        {
            init();
        }

        private function init()
        {
            rs = new RemotingService("http://your.domain.com/amfphp/gateway.php");
            var responder:Responder = new Responder(onResult, onFault);
            var params:Object = new Object();
            params.arg1 = "something";
            params.arg2 = "2";
            rs.call("Class.method", responder, params);
        }

        private function onResult(result:Object):void
        {
            trace(result);
        }

        private function onFault(fault:Object):void
        {
            trace(fault);
        }
    }
}
/*****************************************************************/

Given the following PHP class, the previous exercise could be easily adjusted to print "something and 2" to the Output panel. Just copy it to the 'services' folder of your AMFPHP installation, and replace "Class.method" with "Test.test" on the RemotingTest class.

Save this PHP FILE AS Test.php

/************************ PHP CODE *****************************************/

class Test
{

    function __construct()
    {
        $this->methodTable = array(

                "test" => array(
                "description" => "Tests service",
                "access" => "remote"
            )
        );
    }


    function test($params)
    {
        return $params['arg1'] . " and " . $params['arg2'];
    }

}
?>
/*****************************************************************/