Building a simple chat application using Flex 3 and BlazeDS

This post con­tains the steps to build a sim­ple chat client and server appli­ca­tion using Flex 3 and BlazeDS. This will be a brief post, a detailed tuto­r­ial will be posted in sub­se­quent posts.

1. Deploy the default BlazeDS war file

2. Mod­ify “WEB-INF\flex\messaging-config.xml” to add “SimpleChatDestination”

<?xml version=“1.0″ encoding=“UTF-8″?>
<ser­vice id=“message-service”>

    <adapters>
        <adapter-definition id=“actionscript” default=“true” />
        <!– <adapter-definition id=“jms”/> –>
    </adapters>

    <default-channels>
        <chan­nel ref=“my-polling-amf”/>
    </default-channels>
 
 <des­ti­na­tion id=“SimpleChatDestination”>
  <prop­er­ties>
   <net­work>
    <subscription-timeout-minutes>0</subscription-timeout-minutes>
   </network>
   <server>
    <message-time-to-live>0</message-time-to-live>
    <allow-subtopics>true</allow-subtopics>
    <subtopic-separator>.</subtopic-separator>
   </server>
  </properties>
  <chan­nels>
   <chan­nel ref=“my-polling-amf”/>
  </channels>
 </destination>

</service>

3. Cre­ate a new project in Flex Builder 3 and con­fig­ure it to your BlazeDS deploy­ment. You will need to enter the root folder of the WAR pack­age (usu­ally in “server/default/deploy”), Root URL and Con­text Root.

Configuring BlazeDS while creating project in Flex Builder 3
Con­fig­ur­ing BlazeDS while cre­at­ing project in Flex Builder 3

4. Cre­ate a sim­ple chat client using MXML and Action­Script. Here’s an example:

<?xml version=“1.0″ encoding=“utf-8″?>
<mx:Application xmlns:mx=“
http://www.adobe.com/2006/mxml
 layout=“vertical“
 creationComplete=“consumer.subscribe()”>
 
 <mx:Script>
  <![CDATA[
   import mx.controls.Alert;
   import mx.messaging.messages.AsyncMessage;
   import mx.messaging.messages.IMessage;
   
   pub­lic func­tion send():void {
                var message:IMessage = new AsyncMes­sage();
                message.destination = “Sim­pleChat­Des­ti­na­tion”;
                message.body = “\n” + usernameInput.text + “:\t” + messageInput.text;
               
                trace(producer.connected);
                producer.send(message);
               
                messageInput.text = “”;
   }
   
   pub­lic func­tion mes­sage­Han­dler( message:IMessage ):void {
    textArea.text += message.body;
   }
  ]]>
 </mx:Script>
 
 <mx:Producer id=“producer” destination=“SimpleChatDestination”/>
 
 <mx:Consumer id=“consumer” destination=“SimpleChatDestination” message=“messageHandler(event.message)”/>
 
 <mx:TextArea id=“textArea” width=“400” height=“300”/>
 
 <mx:HBox horizontalGap=“0”>
  <mx:TextInput id=“usernameInput” width=“80”/>
  <mx:TextInput id=“messageInput” width=“180”/>
  <mx:Button label=“Send” click=“send();”/>
 </mx:HBox>
 
</mx:Application>