6.5. The Chat Window

Although the chat window in the example application is part of the entire system, it's actually logically isolated from the market data updating functionality for the most part. You can chat with your investment advisor about the moving prices and that is where the unity exists from a user interaction perspective, but apart from that, the common elements are limited. You can develop the chat application independently of the part that relies on JMS messaging. Let's see how.

The messaging infrastructure in BlazeDS can be utilized for message-based communication between two Flex clients. Messages are routed between the two participating clients via the server. That is, a Flex client sends a message down to a server-side messaging destination via a channel and an endpoint pair. Another Flex client listens for messages at this destination. When a destination receives a message, all subscribers to that destination receive the message.

JMS and the JMSAdapter are not required in this entire interaction. Instead, an ActionScriptAdapter facilitates the communication between the Flex clients. In the next section, you will delve more deeply into these adapters and also learn how to create a custom messaging adapter.

The messaging infrastructure with ActionScriptAdapter supports a publish/subscribe messaging domain. That is, message producers and consumers are coupled together on the basis of an intermediary, which in this case is a topic. This implies that messages sent to a topic will be received by all subscribers. However, sometimes such coarse-grained broadcasting may not be desirable. The messaging infrastructure allows the use of selectors and subtopics to filter messages. Message filtering ensures that only those subscribers who satisfy the filter criteria receive the messages. Although the filtering mechanisms help narrow down the message receivers, it's still a publish/subscribe messaging domain. For point-to-point messaging, you need to either use the JMS queues with the JMS adapter or create a custom adapter to implement such behavior.

Next, the code for the simple chat application is discussed.

6.5.1. The Simple Chat Application

The code for the simple chat application is shown in Listing 6-5.

Example 6.5. The Simple Application for the Chat Window
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
    creationComplete="initApplication();">
        <mx:Script>
            <![CDATA[
                import mx.controls.Alert;
                import mx.messaging.events.MessageEvent;
                import mx.messaging.messages.AsyncMessage;
                import mx.messaging.events.MessageFaultEvent;

                [Bindable]
                private var usersData:Array = new Array("John", "Jane", "Jack",
                 "Jill");

                  private function initApplication():void
                  {
                      messageConsumer.subscribe();
                  }

                  private function showMessages(message:String):void

{
                      chatMessages.text = chatMessages.text + "
" + message;
                  }

                  private function messageHandler(event:MessageEvent):void
                  {
                      var message:String = null;
                      message = event.message.headers["sender"]
                      + ":" + "(to "
                      + event.message.headers["receiver"] + ") " + event.message.
                        body;
                      showMessages(message);
                  }

                  private function sendMessage():void
                  {
                      var message:AsyncMessage = new AsyncMessage();
                      message.headers = new Array();
                      message.headers["sender"] = userName.text;
                      message.headers["receiver"] =
                          users.selectedItem.toString();
                      message.body = chatText.text;
                      messageProducer.send(message);
                      chatText.text = "";
                  }

                  private function faultHandler(event:MessageFaultEvent):void
                  {
                      Alert.show(event.message.body.toString());
                  }


          ]]>
    </mx:Script>

    <mx:Producer id="messageProducer"
        destination="xrchat"
        fault="faultHandler(event);"/>

    <mx:Consumer id="messageConsumer"
        destination="xrchat"
        fault="faultHandler(event)"
        message="messageHandler(event)"/>


    <mx:Panel width="100%" height="100%">
        <mx:VBox width="100%" height="100%">
        <mx:Label text="User Name" />
        <mx:TextInput id="userName" text="...." />
        <mx:List id="users" dataProvider="{usersData}" selectedIndex="0"/>
        </mx:VBox>
        <mx:VBox width="100%" height="100%">
            <mx:Label id="chatArea" text="Chat Messages"/>
            <mx:TextArea id="chatMessages" editable="false" />

<mx:HBox width="100%" height="100%">
                <mx:TextInput id="chatText"  />
                <mx:Button id="chatButton" label="Send" click="sendMessage();"/>
            </mx:HBox>
        </mx:VBox>
    </mx:Panel>

</mx:Application>

This simple application has a message producer and consumer. Both the entities communicate on a single destination, xrchat. From the user interface perspective, there are four important components, which are:

  • A text box in which to enter your name; the value entered in this text box becomes the sender's name

  • A list of names of message receivers

  • A chat message display area

  • A text box and an associated button for sending messages

When you type a message and click the button to send the message out, the sendMessage function is invoked. The sendMessage function creates a new instance of AsyncMessage and then sets the headers and body for that message. Once a message is ready an instance of a message producer's send method is used to send the message. Headers are stored as an Array and are bound to the message through its headers property. A message has BlazeDS-specific headers, which start with the keyword DS and can have custom headers, as shown in the preceding example.

In our simple example, a message consumer subscribes to the same topic to which a producer sends the messages. The consumer defines a message event. On receiving a message, a message listener is triggered. The message listener extracts information from the received message and adds it to the chat message display area.

In order to get this application up and running, you also need to add a messaging destination configuration to messaging-config.xml. The configuration information is:

<destination id="xrchat">
        <properties>
            <network>
                <session-timeout>0</session-timeout>
                <throttle-inbound policy="ERROR" max-frequency="50"/>
                <throttle-outbound policy="REPLACE" max-frequency="500"/>
            </network>
            <server>
                <max-cache-size>1000</max-cache-size>
                <message-time-to-live>0</message-time-to-live>
            </server>
        </properties>

        <channels>
            <channel ref="my-polling-amf"/>

</channels>

        <adapter ref="actionscript"/>
    </destination>

That completes the application. By now, you have seen both the JMSAdapter and the ActionScriptAdapter. Next, you will learn a few things about these two and also explore how a custom adapter can be written and configured.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.141.75