隨著adobe的FLEX和ROMTING的開源化又引起一場的RIA風(fēng)波,我作為傳統(tǒng)的WEB開發(fā)人員被其深深的吸引,作為web開發(fā)人員很關(guān)注flash如何和后臺連接,在網(wǎng)上苦苦尋找終于發(fā)現(xiàn)了,在AS3下如何和后臺通信,其實FLASH ROMTING 和JAVA DWR設(shè)計很相似都是通過中間來轉(zhuǎn)化后臺和前臺對象,今天我就以一個金典的HELLOWORLD程序來展現(xiàn)這個框架。
首先到
http://www.amfphp.org下載AMFPHP1.9,這是目前的最新版本支持AMF3,不像以前的版本1.9版本的部署非常簡單解壓縮后直接拷貝到apache配置的web下面我這里是D:\develop\WebDev\web\amfphp,然后可以測試一下安裝是否成功在地址欄中輸入
http://localhost:8080/amfphp/gateway.php如果看到第一行amfphp and this gateway are installed correctly. You may now connect to this gateway from Flash。說明安裝成功可以進(jìn)行下一步了。
然后寫后臺PHP代碼:Hello.php文件
<?php
class Hello{
function sayHello(){
return "Hello World";
}
}
?>
后臺代碼很簡單,用過1.0版本的人可能發(fā)現(xiàn)這里沒有方法表了(我覺得這個改進(jìn)使得業(yè)務(wù)方法和框架解耦了是個非常好的改進(jìn)),為了簡單這里不講私有g(shù)ateway.php配置直接調(diào)用公有的gateway.php,將Hello.php移動到amfphp\services下面,這樣服務(wù)器端就完成了。
下面是客戶端的編寫:
無意中在網(wǎng)上發(fā)現(xiàn)了一個很好封裝flash.net.Responder, flash.net.NetConnection 這兩個類的代碼這里公布給大家一起學(xué)習(xí)一下

/**//*
Remoting類
負(fù)責(zé)FLASH與數(shù)據(jù)庫交互
*/

package {
import flash.net.Responder;
import flash.net.NetConnection;


public class Remoting extends NetConnection {

/**//*
構(gòu)造
@param gatewayURL remoting網(wǎng)關(guān)地址
@param amfType 使用AMF3或AMF0
*/

public function Remoting(gatewayURL:String,amfType:uint) {
super();
this.objectEncoding=amfType;
this.connect(gatewayURL);
}
//##########################################################################
//
//方法
//
//##########################################################################

/**//*
* 遠(yuǎn)程返回函數(shù)
* @param remoteMethod:遠(yuǎn)程類.方法名param遠(yuǎn)程方法所需要的參數(shù)onResultFun:返回數(shù)據(jù)所調(diào)用的方法句柄.onFaultFun同理.
*
*/

public function respond(remoteMethod:String,onResultFun:*,onFaultFun:*,... param):void {
var parameters:Array=param;

if (param.length > 0) {
parameters.unshift(remoteMethod,new Responder(onResultFun,onFaultFun));
this.call.apply(this,parameters);

} else {
this.call(remoteMethod,new Responder(onResultFun,onFaultFun));
}
}
}
}
然后在任何地方可以調(diào)用它:
var remote:Remoting;
remote=new Remoting("http://localhost/remotinggame/gateway.aspx",0);
remote.respond(remoting方法名,onRuslt,onFault,參數(shù)1,參數(shù)2....);


function onRuslt(re:*):void{
trace(" onRuslt:"+re);
}

function onFault(fe:*):void{
trace(" onFault:"+fe.code);
}
下面用上面封裝的類來實現(xiàn)HELLOWORLD

package {
import flash.display.Sprite;

public class Hello extends Sprite{
private var remoting:Remoting;

public function Hello (){
init();
}

private function init():void{
remoting=new Remoting("http://localhost:8080/amfphp/gateway.php",3);
remoting.respond("Hello.sayHello",onGetData_Ruslt,onGetData_Fault);
}

private function onGetData_Ruslt(re:*):void{
trace(re);
}

private function onGetData_Fault(fe:*):void{

for(var what in fe){
trace(what+" fe:"+fe[what]);
}
}
}
}
posted on 2007-12-13 21:52
飛鳥 閱讀(593)
評論(0) 編輯 收藏 所屬分類:
RIA