Flex与后台通信技术之amfphp与phprpc相较
上次在一位博友flashxm那里看见一篇《用flex连接amfphp》的文章,感觉思路很清楚;就像用phprpc来试试,借此机会向大家介绍phprpc。
博友flashxm的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextArea id="amfphptest" width="200"/>
<mx:Button label="call amfphp" click="callAmfPHP(amfphptest.text)" />
<mx:Script>
<![CDATA[
import flash.net.Responder;
import flash.net.NetConnection;
private var gateway_url:String = "http://www.flashxm.com/amfphp/gateway.php";
private var geteway_conn:NetConnection = new NetConnection();
public function callAmfPHP(str:String):void
{
geteway_conn.connect(gateway_url);
geteway_conn.call("HelloWorld.phpSay", new Responder(onResult, onFault), str);
}
private function onResult(result:Object):void
{
amfphptest.text = result.toString();
}
private function onFault(fault:String):void
{
amfphptest.text = fault;
}
]]>
</mx:Script>
</mx:Application>
服务器端代码:
< ?php
class HelloWorld
{
function HelloWorld()
{
$this->methodTable = array(
‘phpSay’ => array(
‘access’ => ‘remote’
)
);
}
function phpSay($msg)
{
return ‘from PHP >>> ‘ . $msg;
}
}
?>
我写的phprpc:
flex端:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" verticalAlign="middle" horizontalAlign="center">
<mx:Script>
<![CDATA[
import org.phprpc.PHPRPC_Error;
import org.phprpc.PHPRPC_Client;//import PHPRPC_Client
private function clickHandler ( event:MouseEvent ):void
{
var rpc:PHPRPC_Client = new PHPRPC_Client('http://localhost/flex/phprpc/server.php', ['hi']);
//rpc.setEncryptMode(2); 还可以加密传输
rpc.hi(input_value.text, function (result:*, args:Array, output:String, warning:PHPRPC_Error):void {
myLabel.text = result;
});
}
]]>
</mx:Script>
<mx:Panel
title="PHPRPC for Flex" horizontalAlign="center"
paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10"
width="500" height="400">
<mx:TextInput id="input_value"/>
<mx:Button id="myButton" label="Click Me!" click="clickHandler(event);" />
<mx:Label text="" width="135" id="myLabel" fontSize="24"/>
</mx:Panel>
</mx:Application>
服务器端server.php:
<?php
require_once('php/phprpc_server.php');
function hi($input_value){
$h="hello,{$input_value}";
return $h;
}
$server = new PHPRPC_Server();
$server->add('hi');
$server->start();
?>
可以看出,代码更为简洁。
运行结果: