flex 3 + .net开发flash Remoting四 --- 完整代码及Demo下载
flex 3 + .net开发flash Remoting四 --- 完整代码及Demo下载
一. 相关说明:
本篇将呈现完整的Flash Remoting访问远程服务器,包括以可视化组件方式和以编程方式访问远程服务器。Asp.net服务器端和Flex客户端完整代码下载。
二. 相关代码预览:
1.frServices.as,以编程方式访问远程服务器。
 package com.demo.fr
package com.demo.fr
 {
{
 import flash.events.EventDispatcher;
    import flash.events.EventDispatcher;
 import flash.net.NetConnection;
    import flash.net.NetConnection;
 import flash.net.Responder;
    import flash.net.Responder;
 
    
 //用代码调用flash Remoting。
    //用代码调用flash Remoting。
 public class frServices
    public class frServices
 {
    {
 //Remoting服务器对象完整名称。
        //Remoting服务器对象完整名称。
 private var name_ServerClass : String = "Hxw.Demo.FlashRemoting.Hellow";
        private var name_ServerClass : String = "Hxw.Demo.FlashRemoting.Hellow";
 //初始化一个事件广播对象。
        //初始化一个事件广播对象。
 private var eventDispatcher : EventDispatcher = new EventDispatcher();
        private var eventDispatcher : EventDispatcher = new EventDispatcher();        
 //事件关键字定义:Event_KEY_Success_DisplayHellow。
        //事件关键字定义:Event_KEY_Success_DisplayHellow。
 public static var Event_KEY_Success_DisplayHellow : String = "Event_KEY_Success_DisplayHellow";
        public static var Event_KEY_Success_DisplayHellow : String = "Event_KEY_Success_DisplayHellow";
 //事件关键字定义:Event_KEY_Success_SayHellowWorld。
        //事件关键字定义:Event_KEY_Success_SayHellowWorld。
 public static var Event_KEY_Success_SayHellowWorld : String = "Event_KEY_Success_SayHellowWorld";
        public static var Event_KEY_Success_SayHellowWorld : String = "Event_KEY_Success_SayHellowWorld";
 //事件关键字定义:Event_KEY_Success_GetUsers。
        //事件关键字定义:Event_KEY_Success_GetUsers。
 public static var Event_KEY_Success_GetUsers : String = "Event_KEY_Success_GetUsers";
        public static var Event_KEY_Success_GetUsers : String = "Event_KEY_Success_GetUsers";        
 //事件关键字定义:Event_KEY_Fault。
        //事件关键字定义:Event_KEY_Fault。
 public static var Event_KEY_Fault : String = "Event_KEY_Fault";
        public static var Event_KEY_Fault : String = "Event_KEY_Fault";            
 //Remoting连接对象。
        //Remoting连接对象。
 private var conn : NetConnection = null;
        private var conn : NetConnection = null;
 //Flash Remoting方法返回值获取对象。
        //Flash Remoting方法返回值获取对象。
 private var rp :Responder = null;
        private var rp :Responder = null;
 
        
 //构造器。
        //构造器。
 public function frServices()
        public function frServices()
 {
        {
 
            
 }
        }
 
        
 //开始调用远程服务方法。
        //开始调用远程服务方法。
 public function preCall(result : Function):void
        public function preCall(result : Function):void
 {
        {            
 //初始化Remoting连接对象。
            //初始化Remoting连接对象。
 this.conn = new NetConnection();
            this.conn = new NetConnection();            
 //调用connect( )方法,传递进Flash Remoting网关的URL。
            //调用connect( )方法,传递进Flash Remoting网关的URL。
 this.conn.connect("http://localhost:5678/WebFR/Gateway.aspx");
            this.conn.connect("http://localhost:5678/WebFR/Gateway.aspx");            

 this.rp = new Responder(result,onError);
            this.rp = new Responder(result,onError);    
 }
        }
 
        
 //调用远程服务方法。
        //调用远程服务方法。
 public function call_DisplayHellow():void
        public function call_DisplayHellow():void
 {
        {                
 this.preCall(onResult_DisplayHellow);
            this.preCall(onResult_DisplayHellow);
 
            
 //对象的call( )方法调用Flash Remoting方法,call( )方法需要两个参数,
            //对象的call( )方法调用Flash Remoting方法,call( )方法需要两个参数,
 //第一个参数指定方法名称和路径,第二个参数指定响应处理函数,如果不需要处理函数,可直接设为null
            //第一个参数指定方法名称和路径,第二个参数指定响应处理函数,如果不需要处理函数,可直接设为null
 //处理FlashRemoting响应。
            //处理FlashRemoting响应。
 this.conn.call(this.name_ServerClass + ".DisplayHellow",this.rp);
            this.conn.call(this.name_ServerClass + ".DisplayHellow",this.rp);
 }
        }
 
        
 //调用远程服务方法。
        //调用远程服务方法。
 public function call_SayHellowWorld(name : String):void
        public function call_SayHellowWorld(name : String):void
 {
        {
 this.preCall(onResult_SayHellowWorld);
            this.preCall(onResult_SayHellowWorld);
 this.conn.call(this.name_ServerClass + ".SayHellowWorld",this.rp,name);
            this.conn.call(this.name_ServerClass + ".SayHellowWorld",this.rp,name);
 }
        }
 
        
 //调用远程服务方法。
        //调用远程服务方法。
 public function call_GetUsers():void
        public function call_GetUsers():void
 {
        {
 this.preCall(onResult_GetUsers);
            this.preCall(onResult_GetUsers);
 this.conn.call(this.name_ServerClass + ".GetUsers",this.rp);
            this.conn.call(this.name_ServerClass + ".GetUsers",this.rp);
 }
        }        
 
        
 //调用服务成功。
        //调用服务成功。
 private function onResult_DisplayHellow(result : Object) : void
        private function onResult_DisplayHellow(result : Object) : void
 {
        {
 this.resultHandler(result,"DisplayHellow",frServices.Event_KEY_Success_DisplayHellow);
            this.resultHandler(result,"DisplayHellow",frServices.Event_KEY_Success_DisplayHellow);
 }
        }
 
        
 private function onResult_SayHellowWorld(result : Object) : void
        private function onResult_SayHellowWorld(result : Object) : void
 {
        {
 this.resultHandler(result,"SayHellowWorld",frServices.Event_KEY_Success_SayHellowWorld);
            this.resultHandler(result,"SayHellowWorld",frServices.Event_KEY_Success_SayHellowWorld);
 }
        }
 
        
 private function onResult_GetUsers(result : Object) : void
        private function onResult_GetUsers(result : Object) : void
 {
        {
 this.resultHandler(result,"GetUsers",frServices.Event_KEY_Success_GetUsers);
            this.resultHandler(result,"GetUsers",frServices.Event_KEY_Success_GetUsers);
 }
        }        
 
        
 //调用服务成功的处理。
        //调用服务成功的处理。
 private function resultHandler(result : Object,targetName : String ,eventKey : String) : void
        private function resultHandler(result : Object,targetName : String ,eventKey : String) : void
 {
        {
 var ce : CUEvent = new CUEvent(eventKey);
            var ce : CUEvent = new CUEvent(eventKey);
 ce.Sender = result;
            ce.Sender = result;
 ce.CurrentTargetName = targetName;
            ce.CurrentTargetName = targetName;
 
            
 this.eventDispatcher.dispatchEvent(ce);
            this.eventDispatcher.dispatchEvent(ce);
 }
        }
 
        
 //调用服务失败。
        //调用服务失败。
 private function onError(error : Object):void
        private function onError(error : Object):void
 {
        {
 var ce : CUEvent = new CUEvent(Event_KEY_Fault);
            var ce : CUEvent = new CUEvent(Event_KEY_Fault);
 ce.Sender = error;
            ce.Sender = error;
 
            
 this.eventDispatcher.dispatchEvent(ce);
            this.eventDispatcher.dispatchEvent(ce);    
 }
        }
 
        
 //创建一个供外部调用的附加事件侦听的方法。
        //创建一个供外部调用的附加事件侦听的方法。
 public function addEventListener(type : String , listener : Function):void
        public function addEventListener(type : String , listener : Function):void
 {
        {
 this.eventDispatcher.addEventListener(type,listener);
            this.eventDispatcher.addEventListener(type,listener);    
 }
        }

 }
    }
 }
}
2.CUEvent.as,自定义事件。
 package com.demo.fr
package com.demo.fr
 {
{
 import flash.events.Event;
    import flash.events.Event;
 
    
 //从Event继承一个类。
    //从Event继承一个类。
 //为什么as3中仅仅能够定义一个构造器,郁闷。
    //为什么as3中仅仅能够定义一个构造器,郁闷。
 public class CUEvent extends Event
    public class CUEvent extends Event
 {
    {
 //数据实体。
        //数据实体。
 private var _sender : Object = null;
        private var _sender : Object = null;
 //方法名。
        //方法名。
 private var  _currentTargetName: String = "";
        private var  _currentTargetName: String = "";
 
        
 //构造器(为什么as3中仅仅能够定义一个构造器,郁闷)。
        //构造器(为什么as3中仅仅能够定义一个构造器,郁闷)。
 public function CUEvent(type : String,bubbles : Boolean = false,cancelable : Boolean = false)
        public function CUEvent(type : String,bubbles : Boolean = false,cancelable : Boolean = false)
 {
        {
 super(type,bubbles,cancelable);
            super(type,bubbles,cancelable);
 }
        }    
 
        
 //获取 数据实体。
        //获取 数据实体。
 public function get Sender():Object
        public function get Sender():Object
 {
        {
 return this._sender;
            return this._sender;
 }
        }

 //设置 数据实体。
        //设置 数据实体。
 public function set Sender(value : Object) : void
        public function set Sender(value : Object) : void
 {
        {
 this._sender = value;
            this._sender = value;
 }
        }
 
        
 //获取 方法名称。
        //获取 方法名称。
 public function get CurrentTargetName() : String
        public function get CurrentTargetName() : String
 {
        {
 return this._currentTargetName;
            return this._currentTargetName;
 }
        }
 
        
 //设置 方法名称。
        //设置 方法名称。
 public function set CurrentTargetName(value : String) :void
        public function set CurrentTargetName(value : String) :void
 {
        {
 this._currentTargetName = value;
            this._currentTargetName = value;
 }
        }

 }
    }
 }
}
3.User.as,数据模型,对应服务器端的User.cs。
 package com.demo.fr
package com.demo.fr
 {
{
 [RemoteClass(alias="Hxw.Demo.FlashRemoting.User")]
    [RemoteClass(alias="Hxw.Demo.FlashRemoting.User")]
 public class User
    public class User
 {
    {
 public function User()
        public function User()
 {
        {
 }
        }
 
        
 private var _name : String = "";
        private var _name : String = "";
 private var _age : int = 0;
        private var _age : int = 0;
 private var _sex : String = "";
        private var _sex : String = "";
 
        
 public function get Name():String
        public function get Name():String
 {
        {
 return this._name;
            return this._name;
 }
        }
 
        
 public function set Name(v:String):void
        public function set Name(v:String):void
 {
        {
 this._name = v;
            this._name = v;
 }
        }
 
        
 public function get Age():int
        public function get Age():int
 {
        {
 return this._age;
            return this._age;
 }
        }
 
        
 public function set Age(v:int):void
        public function set Age(v:int):void
 {
        {
 this._age = v;
            this._age = v;
 }
        }
 
        
 public function get Sex():String
        public function get Sex():String
 {
        {
 return this._sex;
            return this._sex;
 }
        }
 
        
 public function set Sex(v:String):void
        public function set Sex(v:String):void
 {
        {
 this._sex = v;
            this._sex = v;
 }
        }
 
        
 public function toString():String
        public function toString():String
 {
        {
 return "姓名:" + this._name + ";年龄:" + this._age.toString() + ";性别:" + this._sex;
            return "姓名:" + this._name + ";年龄:" + this._age.toString() + ";性别:" + this._sex;
 }
        }
 }
    }
 }
}
4.MXML Application代码。
 <?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

 <mx:Script>
    <mx:Script>
 < import com.demo.fr.CUEvent;
            import com.demo.fr.CUEvent;
 import flash.net.navigateToURL;
            import flash.net.navigateToURL;
 import mx.collections.ArrayCollection;
            import mx.collections.ArrayCollection;            
 import mx.rpc.events.ResultEvent;
            import mx.rpc.events.ResultEvent;
 import mx.rpc.events.FaultEvent;
            import mx.rpc.events.FaultEvent;
 import mx.controls.Alert;
            import mx.controls.Alert;
 import com.demo.fr.User;
            import com.demo.fr.User;
 import com.demo.fr.frServices;
            import com.demo.fr.frServices;
 import mx.styles.StyleManager;
            import mx.styles.StyleManager;
 
            
 
            
 //1表示以可视化组件方式访问过程服务器。
            //1表示以可视化组件方式访问过程服务器。
//2表示以编程方式访问过程服务器。
 private var mode : int = 2;
            private var mode : int = 2;
 
            
 //调用相关的Remoting服务或模式。
            //调用相关的Remoting服务或模式。
 private function callServer(fn : String):void
            private function callServer(fn : String):void
 {
            {                
 if(this.mode == 1)
                if(this.mode == 1)
 {
                {
 switch(fn)
                    switch(fn)
 {
                    {
 case "DisplayHellow":
                        case "DisplayHellow":
 sampleRemoteObject.DisplayHellow();
                            sampleRemoteObject.DisplayHellow();
 break;
                            break;
 case "SayHellowWorld":
                        case "SayHellowWorld":
 sampleRemoteObject.SayHellowWorld(this.txtMessage.text);
                            sampleRemoteObject.SayHellowWorld(this.txtMessage.text);
 break;
                            break;                        
 case "GetUsers":
                        case "GetUsers":
 sampleRemoteObject.GetUsers();
                            sampleRemoteObject.GetUsers();
 break;
                            break;
 }
                    }
 }
                }
 else
                else
 {
                {
 var fr : frServices = new frServices();
                    var fr : frServices = new frServices();    
 this.addEventListener(frServices.Event_KEY_Fault,onRemoteFault2);
                    this.addEventListener(frServices.Event_KEY_Fault,onRemoteFault2);
 
                    
 switch(fn)
                    switch(fn)
 {
                    {
 case "DisplayHellow":
                        case "DisplayHellow":
 fr.addEventListener(frServices.Event_KEY_Success_DisplayHellow,onRemoteResult2);
                            fr.addEventListener(frServices.Event_KEY_Success_DisplayHellow,onRemoteResult2);
 fr.call_DisplayHellow();
                            fr.call_DisplayHellow();
 break;
                            break;
 case "SayHellowWorld":
                        case "SayHellowWorld":
 fr.addEventListener(frServices.Event_KEY_Success_SayHellowWorld,onRemoteResult2);
                            fr.addEventListener(frServices.Event_KEY_Success_SayHellowWorld,onRemoteResult2);
 fr.call_SayHellowWorld(this.txtMessage.text);
                            fr.call_SayHellowWorld(this.txtMessage.text);
 break;
                            break;                        
 case "GetUsers":
                        case "GetUsers":
 fr.addEventListener(frServices.Event_KEY_Success_GetUsers,onRemoteResult2);
                            fr.addEventListener(frServices.Event_KEY_Success_GetUsers,onRemoteResult2);
 fr.call_GetUsers();
                            fr.call_GetUsers();
 break;
                            break;
 }
                    }
 }
                }
 }
            }
 
            
 
            
 //当Remoting服务调用成功的回调函数(控件调用)。
            //当Remoting服务调用成功的回调函数(控件调用)。
 private function onRemoteResult(event:ResultEvent) : void
            private function onRemoteResult(event:ResultEvent) : void
 {
            {
 this.remoteSuccessHandler(event.result,event.currentTarget.name);
                this.remoteSuccessHandler(event.result,event.currentTarget.name);                
 }
            }
 
            
 //当Remoting服务调用失败的回调函数(控件调用)。
            //当Remoting服务调用失败的回调函数(控件调用)。
 private function onRemoteFault(event:FaultEvent) : void
            private function onRemoteFault(event:FaultEvent) : void
 {
            {
 this.remoteFault(event.fault.toString());
                this.remoteFault(event.fault.toString());
 }
            }        
 
            
 //当Remoting服务调用成功的回调函数(代码实现)。
            //当Remoting服务调用成功的回调函数(代码实现)。
 private function onRemoteResult2(event : CUEvent):void
            private function onRemoteResult2(event : CUEvent):void
 {
            {
 this.remoteSuccessHandler(event.Sender,event.CurrentTargetName);
                this.remoteSuccessHandler(event.Sender,event.CurrentTargetName);
 }
            }

 //当Remoting服务调用失败的回调函数(代码实现)。
            //当Remoting服务调用失败的回调函数(代码实现)。
 private function onRemoteFault2(event : CUEvent) : void
            private function onRemoteFault2(event : CUEvent) : void
 {
            {
 this.remoteFault(event.Sender.toString());
                this.remoteFault(event.Sender.toString());
 }
            }        
 
            
 //当Remoting服务调用成功的处理。
            //当Remoting服务调用成功的处理。
 private function remoteSuccessHandler(data : Object,fn : String):void
            private function remoteSuccessHandler(data : Object,fn : String):void
 {
            {
 switch(fn)
                switch(fn)
 {
                {
 case "DisplayHellow":
                    case "DisplayHellow":
 Alert.show(data as String,"DisplayHellow");
                        Alert.show(data as String,"DisplayHellow");
 break;
                        break;
 case "SayHellowWorld":
                    case "SayHellowWorld":
 Alert.show(data as String,"SayHellowWorld");
                        Alert.show(data as String,"SayHellowWorld");
 break;
                        break;
 case "GetUsers":
                    case "GetUsers":
 var userList : ArrayCollection = data as ArrayCollection;
                        var userList : ArrayCollection = data as ArrayCollection;
 this.dgUsers.dataProvider = userList;
                        this.dgUsers.dataProvider = userList;
 break;
                        break;
 }
                }
 }
            }
 
            
 //当Remoting服务调用失败的处理。
            //当Remoting服务调用失败的处理。
 private function remoteFault(desc:String):void
            private function remoteFault(desc:String):void
 {
            {
 Alert.show(desc,"Remoting调用出错");
                Alert.show(desc,"Remoting调用出错");
 }
            }            

 
            
 //清空DataGrid中的数据。
            //清空DataGrid中的数据。
 private function clearUsers() : void
            private function clearUsers() : void
 {
            {
 this.dgUsers.dataProvider = null;
                this.dgUsers.dataProvider = null;
 }
            }
 
            
 //链接到本人的博客。
            //链接到本人的博客。
 private function getURL():void
            private function getURL():void
 {
            {
 flash.net.navigateToURL(new URLRequest("http://mrhgw.cnblogs.com"));
                flash.net.navigateToURL(new URLRequest("http://mrhgw.cnblogs.com"));
 }
            }    
 
            
 ]]>
        ]]>
 </mx:Script>
    </mx:Script>    
 
    
 <mx:RemoteObject id="sampleRemoteObject"
    <mx:RemoteObject id="sampleRemoteObject"
 destination="fluorine"
        destination="fluorine"
 source="Hxw.Demo.FlashRemoting.Hellow"
        source="Hxw.Demo.FlashRemoting.Hellow"
 showBusyCursor="true">
        showBusyCursor="true">
 
        
 <!--这里是.NET中的方法,name = 方法名 -->
       <!--这里是.NET中的方法,name = 方法名 -->       
 <mx:method name="DisplayHellow" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
        <mx:method name="DisplayHellow" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
 <mx:method name="SayHellowWorld" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
        <mx:method name="SayHellowWorld" result="onRemoteResult(event)" fault="onRemoteFault(event)"/> 
 <mx:method name="GetUsers" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
        <mx:method name="GetUsers" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>        
 </mx:RemoteObject>
    </mx:RemoteObject>
 <mx:Panel layout="absolute" title="Flash Remoting Demo" fontSize="25" right="19" left="19" bottom="67" top="20">
    <mx:Panel layout="absolute" title="Flash Remoting Demo" fontSize="25" right="19" left="19" bottom="67" top="20">
 <mx:TitleWindow x="28" y="29" width="290" height="116" layout="absolute" title="Display Hellow World" fontSize="15">
        <mx:TitleWindow x="28" y="29" width="290" height="116" layout="absolute" title="Display Hellow World" fontSize="15">
 <mx:Button x="10" y="21" label="Call" id="btDisplayHellow" width="120" fontSize="15" click="callServer('DisplayHellow');"/>
            <mx:Button x="10" y="21" label="Call" id="btDisplayHellow" width="120" fontSize="15" click="callServer('DisplayHellow');"/>
 </mx:TitleWindow>
        </mx:TitleWindow>
 <mx:TitleWindow layout="absolute" title="Say Hellow World" top="168" bottom="30" left="28" width="290" fontSize="15">
        <mx:TitleWindow layout="absolute" title="Say Hellow World" top="168" bottom="30" left="28" width="290" fontSize="15">
 <mx:TextInput x="10" y="30" width="232" id="txtMessage" fontSize="13"/>
            <mx:TextInput x="10" y="30" width="232" id="txtMessage" fontSize="13"/>
 <mx:Button x="10" y="76" label="Call" id="btSayHellowWorld" width="120" fontSize="15" click="callServer('SayHellowWorld')"/>
            <mx:Button x="10" y="76" label="Call" id="btSayHellowWorld" width="120" fontSize="15" click="callServer('SayHellowWorld')"/>
 <mx:Label x="10" y="0" text="Name:" fontSize="13" fontWeight="bold"/>
            <mx:Label x="10" y="0" text="Name:" fontSize="13" fontWeight="bold"/>
 </mx:TitleWindow>
        </mx:TitleWindow>
 <mx:TitleWindow layout="absolute" title="Get Users" left="340" right="34" bottom="30" top="29" fontSize="15">
        <mx:TitleWindow layout="absolute" title="Get Users" left="340" right="34" bottom="30" top="29" fontSize="15">
 <mx:Button x="10" y="21" label="Call" id="btGetUser" width="120" fontSize="15" click="callServer('GetUsers')"/>
            <mx:Button x="10" y="21" label="Call" id="btGetUser" width="120" fontSize="15" click="callServer('GetUsers')"/>
 <mx:DataGrid id="dgUsers" fontSize="13" right="10" left="10" top="65" bottom="10">
            <mx:DataGrid id="dgUsers" fontSize="13" right="10" left="10" top="65" bottom="10">
 <mx:columns>
                <mx:columns>
 <mx:DataGridColumn headerText="姓名" dataField="Name"/>
                    <mx:DataGridColumn headerText="姓名" dataField="Name"/>
 <mx:DataGridColumn headerText="性别" dataField="Sex"/>
                    <mx:DataGridColumn headerText="性别" dataField="Sex"/>
 <mx:DataGridColumn headerText="年龄" dataField="Age"/>
                    <mx:DataGridColumn headerText="年龄" dataField="Age"/>
 </mx:columns>
                </mx:columns>
 </mx:DataGrid>
            </mx:DataGrid>
 <mx:Button x="148" y="21" label="Clear" id="btClear" width="120" fontSize="15" click="clearUsers()"/>
            <mx:Button x="148" y="21" label="Clear" id="btClear" width="120" fontSize="15" click="clearUsers()"/>
 </mx:TitleWindow>
        </mx:TitleWindow>
 </mx:Panel>
    </mx:Panel>
 <mx:HRule right="10" left="10" bottom="44" height="10"/>
    <mx:HRule right="10" left="10" bottom="44" height="10"/>
 <mx:LinkButton label="Powered by Hxw(http://mrhgw.cnblogs.com)" fontSize="15" fontStyle="italic" right="45" bottom="8" click="getURL();"/>
    <mx:LinkButton label="Powered by Hxw(http://mrhgw.cnblogs.com)" fontSize="15" fontStyle="italic" right="45" bottom="8" click="getURL();"/>
 
    
 </mx:Application>
</mx:Application>

5. 注意。
在MXML Application的代码中,有代码:private var mode : int = 2;mode值为1表示以可视化组件方式访问远程服务器;mode值为2表示以编程方式访问远程服务器。
三. Demo下载。
1. ASP.NET服务器端代码 下载 。
2. Flex客户端代码 下载 。
四. 结束语。
flex 3 + .net开发flash Remoting本系列文章至此结束,如有谬误敬请指正,欢迎一起学习交流。
一. 相关说明:
本篇将呈现完整的Flash Remoting访问远程服务器,包括以可视化组件方式和以编程方式访问远程服务器。Asp.net服务器端和Flex客户端完整代码下载。
二. 相关代码预览:
1.frServices.as,以编程方式访问远程服务器。
 package com.demo.fr
package com.demo.fr {
{ import flash.events.EventDispatcher;
    import flash.events.EventDispatcher; import flash.net.NetConnection;
    import flash.net.NetConnection; import flash.net.Responder;
    import flash.net.Responder; 
     //用代码调用flash Remoting。
    //用代码调用flash Remoting。 public class frServices
    public class frServices {
    { //Remoting服务器对象完整名称。
        //Remoting服务器对象完整名称。 private var name_ServerClass : String = "Hxw.Demo.FlashRemoting.Hellow";
        private var name_ServerClass : String = "Hxw.Demo.FlashRemoting.Hellow"; //初始化一个事件广播对象。
        //初始化一个事件广播对象。 private var eventDispatcher : EventDispatcher = new EventDispatcher();
        private var eventDispatcher : EventDispatcher = new EventDispatcher();         //事件关键字定义:Event_KEY_Success_DisplayHellow。
        //事件关键字定义:Event_KEY_Success_DisplayHellow。 public static var Event_KEY_Success_DisplayHellow : String = "Event_KEY_Success_DisplayHellow";
        public static var Event_KEY_Success_DisplayHellow : String = "Event_KEY_Success_DisplayHellow"; //事件关键字定义:Event_KEY_Success_SayHellowWorld。
        //事件关键字定义:Event_KEY_Success_SayHellowWorld。 public static var Event_KEY_Success_SayHellowWorld : String = "Event_KEY_Success_SayHellowWorld";
        public static var Event_KEY_Success_SayHellowWorld : String = "Event_KEY_Success_SayHellowWorld"; //事件关键字定义:Event_KEY_Success_GetUsers。
        //事件关键字定义:Event_KEY_Success_GetUsers。 public static var Event_KEY_Success_GetUsers : String = "Event_KEY_Success_GetUsers";
        public static var Event_KEY_Success_GetUsers : String = "Event_KEY_Success_GetUsers";         //事件关键字定义:Event_KEY_Fault。
        //事件关键字定义:Event_KEY_Fault。 public static var Event_KEY_Fault : String = "Event_KEY_Fault";
        public static var Event_KEY_Fault : String = "Event_KEY_Fault";             //Remoting连接对象。
        //Remoting连接对象。 private var conn : NetConnection = null;
        private var conn : NetConnection = null; //Flash Remoting方法返回值获取对象。
        //Flash Remoting方法返回值获取对象。 private var rp :Responder = null;
        private var rp :Responder = null; 
         //构造器。
        //构造器。 public function frServices()
        public function frServices() {
        { 
             }
        } 
         //开始调用远程服务方法。
        //开始调用远程服务方法。 public function preCall(result : Function):void
        public function preCall(result : Function):void {
        {             //初始化Remoting连接对象。
            //初始化Remoting连接对象。 this.conn = new NetConnection();
            this.conn = new NetConnection();             //调用connect( )方法,传递进Flash Remoting网关的URL。
            //调用connect( )方法,传递进Flash Remoting网关的URL。 this.conn.connect("http://localhost:5678/WebFR/Gateway.aspx");
            this.conn.connect("http://localhost:5678/WebFR/Gateway.aspx");            
 this.rp = new Responder(result,onError);
            this.rp = new Responder(result,onError);     }
        } 
         //调用远程服务方法。
        //调用远程服务方法。 public function call_DisplayHellow():void
        public function call_DisplayHellow():void {
        {                 this.preCall(onResult_DisplayHellow);
            this.preCall(onResult_DisplayHellow); 
             //对象的call( )方法调用Flash Remoting方法,call( )方法需要两个参数,
            //对象的call( )方法调用Flash Remoting方法,call( )方法需要两个参数, //第一个参数指定方法名称和路径,第二个参数指定响应处理函数,如果不需要处理函数,可直接设为null
            //第一个参数指定方法名称和路径,第二个参数指定响应处理函数,如果不需要处理函数,可直接设为null //处理FlashRemoting响应。
            //处理FlashRemoting响应。 this.conn.call(this.name_ServerClass + ".DisplayHellow",this.rp);
            this.conn.call(this.name_ServerClass + ".DisplayHellow",this.rp); }
        } 
         //调用远程服务方法。
        //调用远程服务方法。 public function call_SayHellowWorld(name : String):void
        public function call_SayHellowWorld(name : String):void {
        { this.preCall(onResult_SayHellowWorld);
            this.preCall(onResult_SayHellowWorld); this.conn.call(this.name_ServerClass + ".SayHellowWorld",this.rp,name);
            this.conn.call(this.name_ServerClass + ".SayHellowWorld",this.rp,name); }
        } 
         //调用远程服务方法。
        //调用远程服务方法。 public function call_GetUsers():void
        public function call_GetUsers():void {
        { this.preCall(onResult_GetUsers);
            this.preCall(onResult_GetUsers); this.conn.call(this.name_ServerClass + ".GetUsers",this.rp);
            this.conn.call(this.name_ServerClass + ".GetUsers",this.rp); }
        }         
         //调用服务成功。
        //调用服务成功。 private function onResult_DisplayHellow(result : Object) : void
        private function onResult_DisplayHellow(result : Object) : void {
        { this.resultHandler(result,"DisplayHellow",frServices.Event_KEY_Success_DisplayHellow);
            this.resultHandler(result,"DisplayHellow",frServices.Event_KEY_Success_DisplayHellow); }
        } 
         private function onResult_SayHellowWorld(result : Object) : void
        private function onResult_SayHellowWorld(result : Object) : void {
        { this.resultHandler(result,"SayHellowWorld",frServices.Event_KEY_Success_SayHellowWorld);
            this.resultHandler(result,"SayHellowWorld",frServices.Event_KEY_Success_SayHellowWorld); }
        } 
         private function onResult_GetUsers(result : Object) : void
        private function onResult_GetUsers(result : Object) : void {
        { this.resultHandler(result,"GetUsers",frServices.Event_KEY_Success_GetUsers);
            this.resultHandler(result,"GetUsers",frServices.Event_KEY_Success_GetUsers); }
        }         
         //调用服务成功的处理。
        //调用服务成功的处理。 private function resultHandler(result : Object,targetName : String ,eventKey : String) : void
        private function resultHandler(result : Object,targetName : String ,eventKey : String) : void {
        { var ce : CUEvent = new CUEvent(eventKey);
            var ce : CUEvent = new CUEvent(eventKey); ce.Sender = result;
            ce.Sender = result; ce.CurrentTargetName = targetName;
            ce.CurrentTargetName = targetName; 
             this.eventDispatcher.dispatchEvent(ce);
            this.eventDispatcher.dispatchEvent(ce); }
        } 
         //调用服务失败。
        //调用服务失败。 private function onError(error : Object):void
        private function onError(error : Object):void {
        { var ce : CUEvent = new CUEvent(Event_KEY_Fault);
            var ce : CUEvent = new CUEvent(Event_KEY_Fault); ce.Sender = error;
            ce.Sender = error; 
             this.eventDispatcher.dispatchEvent(ce);
            this.eventDispatcher.dispatchEvent(ce);     }
        } 
         //创建一个供外部调用的附加事件侦听的方法。
        //创建一个供外部调用的附加事件侦听的方法。 public function addEventListener(type : String , listener : Function):void
        public function addEventListener(type : String , listener : Function):void {
        { this.eventDispatcher.addEventListener(type,listener);
            this.eventDispatcher.addEventListener(type,listener);     }
        }
 }
    } }
}2.CUEvent.as,自定义事件。
 package com.demo.fr
package com.demo.fr {
{ import flash.events.Event;
    import flash.events.Event; 
     //从Event继承一个类。
    //从Event继承一个类。 //为什么as3中仅仅能够定义一个构造器,郁闷。
    //为什么as3中仅仅能够定义一个构造器,郁闷。 public class CUEvent extends Event
    public class CUEvent extends Event {
    { //数据实体。
        //数据实体。 private var _sender : Object = null;
        private var _sender : Object = null; //方法名。
        //方法名。 private var  _currentTargetName: String = "";
        private var  _currentTargetName: String = ""; 
         //构造器(为什么as3中仅仅能够定义一个构造器,郁闷)。
        //构造器(为什么as3中仅仅能够定义一个构造器,郁闷)。 public function CUEvent(type : String,bubbles : Boolean = false,cancelable : Boolean = false)
        public function CUEvent(type : String,bubbles : Boolean = false,cancelable : Boolean = false) {
        { super(type,bubbles,cancelable);
            super(type,bubbles,cancelable); }
        }     
         //获取 数据实体。
        //获取 数据实体。 public function get Sender():Object
        public function get Sender():Object {
        { return this._sender;
            return this._sender; }
        }
 //设置 数据实体。
        //设置 数据实体。 public function set Sender(value : Object) : void
        public function set Sender(value : Object) : void {
        { this._sender = value;
            this._sender = value; }
        } 
         //获取 方法名称。
        //获取 方法名称。 public function get CurrentTargetName() : String
        public function get CurrentTargetName() : String {
        { return this._currentTargetName;
            return this._currentTargetName; }
        } 
         //设置 方法名称。
        //设置 方法名称。 public function set CurrentTargetName(value : String) :void
        public function set CurrentTargetName(value : String) :void {
        { this._currentTargetName = value;
            this._currentTargetName = value; }
        }
 }
    } }
}3.User.as,数据模型,对应服务器端的User.cs。
 package com.demo.fr
package com.demo.fr {
{ [RemoteClass(alias="Hxw.Demo.FlashRemoting.User")]
    [RemoteClass(alias="Hxw.Demo.FlashRemoting.User")] public class User
    public class User {
    { public function User()
        public function User() {
        { }
        } 
         private var _name : String = "";
        private var _name : String = ""; private var _age : int = 0;
        private var _age : int = 0; private var _sex : String = "";
        private var _sex : String = ""; 
         public function get Name():String
        public function get Name():String {
        { return this._name;
            return this._name; }
        } 
         public function set Name(v:String):void
        public function set Name(v:String):void {
        { this._name = v;
            this._name = v; }
        } 
         public function get Age():int
        public function get Age():int {
        { return this._age;
            return this._age; }
        } 
         public function set Age(v:int):void
        public function set Age(v:int):void {
        { this._age = v;
            this._age = v; }
        } 
         public function get Sex():String
        public function get Sex():String {
        { return this._sex;
            return this._sex; }
        } 
         public function set Sex(v:String):void
        public function set Sex(v:String):void {
        { this._sex = v;
            this._sex = v; }
        } 
         public function toString():String
        public function toString():String {
        { return "姓名:" + this._name + ";年龄:" + this._age.toString() + ";性别:" + this._sex;
            return "姓名:" + this._name + ";年龄:" + this._age.toString() + ";性别:" + this._sex; }
        } }
    } }
}4.MXML Application代码。
 <?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 <mx:Script>
    <mx:Script> < import com.demo.fr.CUEvent;
            import com.demo.fr.CUEvent; import flash.net.navigateToURL;
            import flash.net.navigateToURL; import mx.collections.ArrayCollection;
            import mx.collections.ArrayCollection;             import mx.rpc.events.ResultEvent;
            import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent;
            import mx.rpc.events.FaultEvent; import mx.controls.Alert;
            import mx.controls.Alert; import com.demo.fr.User;
            import com.demo.fr.User; import com.demo.fr.frServices;
            import com.demo.fr.frServices; import mx.styles.StyleManager;
            import mx.styles.StyleManager; 
             
             //1表示以可视化组件方式访问过程服务器。
            //1表示以可视化组件方式访问过程服务器。//2表示以编程方式访问过程服务器。
 private var mode : int = 2;
            private var mode : int = 2; 
             //调用相关的Remoting服务或模式。
            //调用相关的Remoting服务或模式。 private function callServer(fn : String):void
            private function callServer(fn : String):void {
            {                 if(this.mode == 1)
                if(this.mode == 1) {
                { switch(fn)
                    switch(fn) {
                    { case "DisplayHellow":
                        case "DisplayHellow": sampleRemoteObject.DisplayHellow();
                            sampleRemoteObject.DisplayHellow(); break;
                            break; case "SayHellowWorld":
                        case "SayHellowWorld": sampleRemoteObject.SayHellowWorld(this.txtMessage.text);
                            sampleRemoteObject.SayHellowWorld(this.txtMessage.text); break;
                            break;                         case "GetUsers":
                        case "GetUsers": sampleRemoteObject.GetUsers();
                            sampleRemoteObject.GetUsers(); break;
                            break; }
                    } }
                } else
                else {
                { var fr : frServices = new frServices();
                    var fr : frServices = new frServices();     this.addEventListener(frServices.Event_KEY_Fault,onRemoteFault2);
                    this.addEventListener(frServices.Event_KEY_Fault,onRemoteFault2); 
                     switch(fn)
                    switch(fn) {
                    { case "DisplayHellow":
                        case "DisplayHellow": fr.addEventListener(frServices.Event_KEY_Success_DisplayHellow,onRemoteResult2);
                            fr.addEventListener(frServices.Event_KEY_Success_DisplayHellow,onRemoteResult2); fr.call_DisplayHellow();
                            fr.call_DisplayHellow(); break;
                            break; case "SayHellowWorld":
                        case "SayHellowWorld": fr.addEventListener(frServices.Event_KEY_Success_SayHellowWorld,onRemoteResult2);
                            fr.addEventListener(frServices.Event_KEY_Success_SayHellowWorld,onRemoteResult2); fr.call_SayHellowWorld(this.txtMessage.text);
                            fr.call_SayHellowWorld(this.txtMessage.text); break;
                            break;                         case "GetUsers":
                        case "GetUsers": fr.addEventListener(frServices.Event_KEY_Success_GetUsers,onRemoteResult2);
                            fr.addEventListener(frServices.Event_KEY_Success_GetUsers,onRemoteResult2); fr.call_GetUsers();
                            fr.call_GetUsers(); break;
                            break; }
                    } }
                } }
            } 
             
             //当Remoting服务调用成功的回调函数(控件调用)。
            //当Remoting服务调用成功的回调函数(控件调用)。 private function onRemoteResult(event:ResultEvent) : void
            private function onRemoteResult(event:ResultEvent) : void {
            { this.remoteSuccessHandler(event.result,event.currentTarget.name);
                this.remoteSuccessHandler(event.result,event.currentTarget.name);                 }
            } 
             //当Remoting服务调用失败的回调函数(控件调用)。
            //当Remoting服务调用失败的回调函数(控件调用)。 private function onRemoteFault(event:FaultEvent) : void
            private function onRemoteFault(event:FaultEvent) : void {
            { this.remoteFault(event.fault.toString());
                this.remoteFault(event.fault.toString()); }
            }         
             //当Remoting服务调用成功的回调函数(代码实现)。
            //当Remoting服务调用成功的回调函数(代码实现)。 private function onRemoteResult2(event : CUEvent):void
            private function onRemoteResult2(event : CUEvent):void {
            { this.remoteSuccessHandler(event.Sender,event.CurrentTargetName);
                this.remoteSuccessHandler(event.Sender,event.CurrentTargetName); }
            }
 //当Remoting服务调用失败的回调函数(代码实现)。
            //当Remoting服务调用失败的回调函数(代码实现)。 private function onRemoteFault2(event : CUEvent) : void
            private function onRemoteFault2(event : CUEvent) : void {
            { this.remoteFault(event.Sender.toString());
                this.remoteFault(event.Sender.toString()); }
            }         
             //当Remoting服务调用成功的处理。
            //当Remoting服务调用成功的处理。 private function remoteSuccessHandler(data : Object,fn : String):void
            private function remoteSuccessHandler(data : Object,fn : String):void {
            { switch(fn)
                switch(fn) {
                { case "DisplayHellow":
                    case "DisplayHellow": Alert.show(data as String,"DisplayHellow");
                        Alert.show(data as String,"DisplayHellow"); break;
                        break; case "SayHellowWorld":
                    case "SayHellowWorld": Alert.show(data as String,"SayHellowWorld");
                        Alert.show(data as String,"SayHellowWorld"); break;
                        break; case "GetUsers":
                    case "GetUsers": var userList : ArrayCollection = data as ArrayCollection;
                        var userList : ArrayCollection = data as ArrayCollection; this.dgUsers.dataProvider = userList;
                        this.dgUsers.dataProvider = userList; break;
                        break; }
                } }
            } 
             //当Remoting服务调用失败的处理。
            //当Remoting服务调用失败的处理。 private function remoteFault(desc:String):void
            private function remoteFault(desc:String):void {
            { Alert.show(desc,"Remoting调用出错");
                Alert.show(desc,"Remoting调用出错"); }
            }            
 
             //清空DataGrid中的数据。
            //清空DataGrid中的数据。 private function clearUsers() : void
            private function clearUsers() : void {
            { this.dgUsers.dataProvider = null;
                this.dgUsers.dataProvider = null; }
            } 
             //链接到本人的博客。
            //链接到本人的博客。 private function getURL():void
            private function getURL():void {
            { flash.net.navigateToURL(new URLRequest("http://mrhgw.cnblogs.com"));
                flash.net.navigateToURL(new URLRequest("http://mrhgw.cnblogs.com")); }
            }     
             ]]>
        ]]> </mx:Script>
    </mx:Script>     
     <mx:RemoteObject id="sampleRemoteObject"
    <mx:RemoteObject id="sampleRemoteObject" destination="fluorine"
        destination="fluorine" source="Hxw.Demo.FlashRemoting.Hellow"
        source="Hxw.Demo.FlashRemoting.Hellow" showBusyCursor="true">
        showBusyCursor="true"> 
         <!--这里是.NET中的方法,name = 方法名 -->
       <!--这里是.NET中的方法,name = 方法名 -->        <mx:method name="DisplayHellow" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
        <mx:method name="DisplayHellow" result="onRemoteResult(event)" fault="onRemoteFault(event)"/> <mx:method name="SayHellowWorld" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
        <mx:method name="SayHellowWorld" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>  <mx:method name="GetUsers" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>
        <mx:method name="GetUsers" result="onRemoteResult(event)" fault="onRemoteFault(event)"/>         </mx:RemoteObject>
    </mx:RemoteObject> <mx:Panel layout="absolute" title="Flash Remoting Demo" fontSize="25" right="19" left="19" bottom="67" top="20">
    <mx:Panel layout="absolute" title="Flash Remoting Demo" fontSize="25" right="19" left="19" bottom="67" top="20"> <mx:TitleWindow x="28" y="29" width="290" height="116" layout="absolute" title="Display Hellow World" fontSize="15">
        <mx:TitleWindow x="28" y="29" width="290" height="116" layout="absolute" title="Display Hellow World" fontSize="15"> <mx:Button x="10" y="21" label="Call" id="btDisplayHellow" width="120" fontSize="15" click="callServer('DisplayHellow');"/>
            <mx:Button x="10" y="21" label="Call" id="btDisplayHellow" width="120" fontSize="15" click="callServer('DisplayHellow');"/> </mx:TitleWindow>
        </mx:TitleWindow> <mx:TitleWindow layout="absolute" title="Say Hellow World" top="168" bottom="30" left="28" width="290" fontSize="15">
        <mx:TitleWindow layout="absolute" title="Say Hellow World" top="168" bottom="30" left="28" width="290" fontSize="15"> <mx:TextInput x="10" y="30" width="232" id="txtMessage" fontSize="13"/>
            <mx:TextInput x="10" y="30" width="232" id="txtMessage" fontSize="13"/> <mx:Button x="10" y="76" label="Call" id="btSayHellowWorld" width="120" fontSize="15" click="callServer('SayHellowWorld')"/>
            <mx:Button x="10" y="76" label="Call" id="btSayHellowWorld" width="120" fontSize="15" click="callServer('SayHellowWorld')"/> <mx:Label x="10" y="0" text="Name:" fontSize="13" fontWeight="bold"/>
            <mx:Label x="10" y="0" text="Name:" fontSize="13" fontWeight="bold"/> </mx:TitleWindow>
        </mx:TitleWindow> <mx:TitleWindow layout="absolute" title="Get Users" left="340" right="34" bottom="30" top="29" fontSize="15">
        <mx:TitleWindow layout="absolute" title="Get Users" left="340" right="34" bottom="30" top="29" fontSize="15"> <mx:Button x="10" y="21" label="Call" id="btGetUser" width="120" fontSize="15" click="callServer('GetUsers')"/>
            <mx:Button x="10" y="21" label="Call" id="btGetUser" width="120" fontSize="15" click="callServer('GetUsers')"/> <mx:DataGrid id="dgUsers" fontSize="13" right="10" left="10" top="65" bottom="10">
            <mx:DataGrid id="dgUsers" fontSize="13" right="10" left="10" top="65" bottom="10"> <mx:columns>
                <mx:columns> <mx:DataGridColumn headerText="姓名" dataField="Name"/>
                    <mx:DataGridColumn headerText="姓名" dataField="Name"/> <mx:DataGridColumn headerText="性别" dataField="Sex"/>
                    <mx:DataGridColumn headerText="性别" dataField="Sex"/> <mx:DataGridColumn headerText="年龄" dataField="Age"/>
                    <mx:DataGridColumn headerText="年龄" dataField="Age"/> </mx:columns>
                </mx:columns> </mx:DataGrid>
            </mx:DataGrid> <mx:Button x="148" y="21" label="Clear" id="btClear" width="120" fontSize="15" click="clearUsers()"/>
            <mx:Button x="148" y="21" label="Clear" id="btClear" width="120" fontSize="15" click="clearUsers()"/> </mx:TitleWindow>
        </mx:TitleWindow> </mx:Panel>
    </mx:Panel> <mx:HRule right="10" left="10" bottom="44" height="10"/>
    <mx:HRule right="10" left="10" bottom="44" height="10"/> <mx:LinkButton label="Powered by Hxw(http://mrhgw.cnblogs.com)" fontSize="15" fontStyle="italic" right="45" bottom="8" click="getURL();"/>
    <mx:LinkButton label="Powered by Hxw(http://mrhgw.cnblogs.com)" fontSize="15" fontStyle="italic" right="45" bottom="8" click="getURL();"/> 
     </mx:Application>
</mx:Application>
5. 注意。
在MXML Application的代码中,有代码:private var mode : int = 2;mode值为1表示以可视化组件方式访问远程服务器;mode值为2表示以编程方式访问远程服务器。
三. Demo下载。
1. ASP.NET服务器端代码 下载 。
2. Flex客户端代码 下载 。
四. 结束语。
flex 3 + .net开发flash Remoting本系列文章至此结束,如有谬误敬请指正,欢迎一起学习交流。
 
                    
                
 


 
     
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号