| Flex 2 Developer's Guide > Data Access and Interconnectivity > Using Flex Messaging > Using a pair of Producer and Consumer components in an application | |||
A Flex application often contains at least one pair of Producer and Consumer components. This enables each application to send messages to a destination and receive messages that other applications send to that destination.
To act as a pair, Producer and Consumer components in an application must use the same message destination. Producer component instances send messages to a destination, and Consumer component instances receive messages from that destination.
The following code shows excerpts from a simple chat application that contains a pair of Producer and Consumer components. The user types messages in a msg TextInput control; the Producer component sends the message when the user presses the keyboard Enter key or clicks the Button control labeled Send. The user views messages from other users in the ta TextArea control. The user can switch between non-JMS and JMS-enabled destinations by selecting items in the topics List control.
<?xml version="1.0"?>
<!-- fds\messaging\ProducerConsumer.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.messaging.messages.*;
import mx.messaging.events.*;
private function logon():void {
producer.destination = topics.selectedItem.toString();
consumer.destination = topics.selectedItem.toString();
consumer.subscribe();
topics.selectedIndex = 1;
}
private function messageHandler(event: MessageEvent):void {
ta.text += event.message.body + "\n";
}
private function sendMessage():void {
var message: AsyncMessage = new AsyncMessage();
message.body = userName.text + ": " + msg.text;
producer.send(message);
msg.text = "";
}
]]>
</mx:Script>
<mx:Producer id="producer" destination="ChatTopicJMS"/>
<mx:Consumer id="consumer" destination="ChatTopicJMS"
message="messageHandler(event)"/>
<mx:List id="topics">
<mx:dataProvider>
<mx:ArrayCollection>
<mx:String>chat-topic</mx:String>
<mx:String>chat-topic-jms</mx:String>
</mx:ArrayCollection>
</mx:dataProvider>
</mx:List>
<mx:TextArea id="ta" width="100%" height="100%"/>
<mx:TextInput id="userName" width="100%"/>
<mx:TextInput id="msg" width="100%"/>
<mx:Button label="Send" click="sendMessage()"/>
</mx:Application>
|
NOTE |
|
The Flex sample applications include the code for the complete chat application. |
Flex 2.01