Pages

Sunday, January 15, 2012

AS3: Flex to Web-service Communicator

Here is a flex to web-service communicator. It dispatches a package of data to the server and receives the result in response from the server.
package engine
{ 
 
 /**
  * @file CCommunicator.as
  * @author Abhishek Kumar
  */
 
 import mx.rpc.http.HTTPService;
 import com.sephiroth.Serializer;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.events.FaultEvent;
 import mx.controls.Alert;
 import engine.CUtility;
 
 public class CCommunicator
 {  
  private var communicationAgent:HTTPService;
  private var communicationUrl:String;
  private var communicationProceed:Function;
  
  /* Ex:
   * public var oCommunicator:Object = new CCommunicator();
   */
  public function CCommunicator():void
  {
   //trace('CCommunicator');
  }
  
  /* Ex:
   * <mx:HTTPService id="transmittingAgent" url="<url-link>" result="oCommunicator.receiveDataFromServer(event);" fault="oCommunicator.handleCommunicationFault(event);" useProxy="false" method="POST" resultFormat="text" />
   * oCommunicator.setCommunicator(transmittingAgent);
   */
  public function setCommunicator(iEntity:HTTPService):void
  {
   communicationAgent = iEntity;   
  }
  
  /* Ex:
   * oCommunicator.setUrl();
   */
  public function setUrl(iUrl:String):void
  {
   communicationUrl = iUrl;
  }
  
  /* Ex:
   * oCommunicator.setProceed();
   */
  public function setProceed(iProcedure:Function):void
  {
   communicationProceed = iProcedure;
  }
  
  /* Ex:
   * oCommunicator.initialize();
   */
  public function initialize():void 
  {
      communicationAgent = new HTTPService();
      communicationAgent.url = communicationUrl; 
      communicationAgent.method = "POST";
      communicationAgent.addEventListener("result", receiveDataFromServer);
      communicationAgent.addEventListener("fault", handleCommunicationFault);
  }
  
  private function receiveDataFromServer(event:ResultEvent):void
  {
   var receivedDataFromServer:String = CUtility.filter(event.result.toString());
   var extractedInformationFromReceivedData:Object = Serializer.unserialize(unescape(receivedDataFromServer));
   communicationProceed(extractedInformationFromReceivedData);
  }
  
  private function handleCommunicationFault(event:FaultEvent):void
  {
   Alert.show(event.fault.faultString, 'Error');
  }
  
  public function sendDataToServer(iReturn:Boolean, iQuery:String):void
  {
   var packagedData:Object = {COMMAND:iReturn, QUERY:iQuery};
   var transmittingDataToServer:String = Serializer.serialize(packagedData);
   communicationAgent.send({message:transmittingDataToServer});
  } 
 }  
}

package engine
{
 /**
  * @file CUtility.as
  * @author Abhishek Kumar
  */
 public class CUtility
 {  
  public function CUtility() 
  {   
  }  
  public static function filter(iMsg:String):String
  {
   return iMsg.split('+').join(' ');
  }  
 }
}

No comments:

Post a Comment