miércoles, 7 de abril de 2010

Communications between two Local Flex Apps - Comicacion entre dos Apps de Flex Locales


Translation:

Algunas veces queremos comunicar dos aplicaciones de Flex o Flash que se encuentran en la misma página, y no vemos la manera de hacerlo.

ActionScript tiene una clase, que nos permite hacer esto sin mucho esfuerzo. Esta clase está ubicada en flash.net. LocalConnection.

Como todo principio de Cliente servidor, una aplicación tiene que escuchar y la otra tiene que ver si hay alguien escuchando.

Veamos el primer código donde vemos la aplicación que escucha, le colocaremos un nombre a la conexión llamada myConnection:
Sometimes we want to communicate two Flex or Flash applications that are on the same page, and do not see how.

ActionScript has a class, allowing us to do so without much effort. This class is located at flash.net. LocalConnection.

The idea is like a client server connection, an application needs to listen and the other has to see if anyone is listening.

Let us first see the application code where you hear, we will place a name to the connection called myConnection:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="500" minHeight="300"
      applicationComplete="applicationCompleteHandler(event)" viewSourceURL="srcview/index.html">
 

 
 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.FlexEvent;
   
   private const connection:LocalConnection = new LocalConnection();
[Bindable] private var   data:ArrayCollection = new ArrayCollection();
   
   protected function applicationCompleteHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Application Complete Handler");
    connection.client = this;
    connection.connect("myConnection");
    data.addItem("The Client es THE APP, The name is myConnection");
   }
   
   public function colorBackground(sendedColor:uint):void
   {
    data.addItem("colorBackground Function");
    try
    {
     remoteColor.setStyle("backgroundColor",sendedColor);
     data.addItem("Recived Color in UInt -> "+ sendedColor);
    }
    catch (error:ArgumentError)
    {
     Alert.show("Error trying to connect to LocalConnection.");
    }
   } 
   
  ]]>
 </fx:Script>
 
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 
 <s:VGroup height="100%" width="100%" 
     x="0" y="0" 
     paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20" 
     horizontalAlign="center">
  <s:Panel id="remoteColor" 
     width="250" height="100" 
     title="Remote Background Color" >
  </s:Panel>
  <s:Panel width="100%" height="100%" 
     title="Console">
   <s:List id="console" 
     width="100%" height="100%" 
     x="0" y="0"
     dataProvider="{data}"></s:List>
  </s:Panel>
 </s:VGroup>
</s:Application>

Ahora veamos la segundo aplicación la cual envía un mensaje a myConnection buscando una función llamada colorBackground y le pasa como parámetro el Color Seleccionado:
Now for the second application which sends a message looking for a function called myConnection colorBackground and passes as parameters the Selected Color:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx" 
      minWidth="500" minHeight="300"
      applicationComplete="applicationCompleteHandler(event)" viewSourceURL="srcview/index.html">
 
 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.ColorPickerEvent;
   import mx.events.FlexEvent;
   
   private const connection:LocalConnection = new LocalConnection();
[Bindable] private var   data:ArrayCollection = new ArrayCollection();
   protected function applicationCompleteHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Application Complete Handler");
    connection.addEventListener(StatusEvent.STATUS, connectionStatusHandler);
    data.addItem("Add Listener Status to the Connection");
   }
   
   private function connectionStatusHandler(event:StatusEvent):void
   {
    data.addItem("Connection Status Handler");
    switch (event.level)
    {
     case "status":
      trace("Use of LocalConnection.send() succeeded");
      break;
     case "error":
      Alert.show(
       "The LocalConnection.send() call failed: "
       + event.code + "\n"
       + event.toString() );
      break;
    }
    data.addItem("Status -> "+ event.level );
   }
   
   protected function sendColorHandler(event:ColorPickerEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Send Color Handler");
    connection.send("myConnection", "colorBackground", event.color);
    data.addItem("Color Sending in UInt -> " + event.color);
   }
  ]]>
 </fx:Script>
 
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 <s:VGroup x="0" y="0" 
     width="100%" height="100%" 
     paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20" 
     horizontalAlign="center">
  <mx:ColorPicker change="sendColorHandler(event)"/>
  <s:Panel width="100%" height="100%" 
     title="Console">
   <s:List id="console" 
     x="0" y="0" 
     width="100%" height="100%"
     dataProvider="{data}"></s:List>
  </s:Panel>
 </s:VGroup>
</s:Application>


Los archivos pueden Descargarlos arriba de cada ejemplo.
The files can be downloaded above each example.

Ejemplo Uno - Recive el mensaje:
Example One - The message receiver:

Ver y Descargar Archivo del App 1:
View Source and Download Files of the App 1:


Ejemplo Dos - Envia el Mensaje:
Example Two - Sends the Message:

Ver y Descargar Archivo del App 2:
View Source and Download Files of the App 2:

No hay comentarios.:

Publicar un comentario