A Flex application often contains at least one pair of Producer and Consumer components. This configuration 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 a simple chat application that contains a pair of Producer and Consumer components. The user types messages in a 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. If you open this application in two browser windows, any message sent by one instance of the application appears in both.
<?xml version="1.0"?>
<!-- ds\messaging\ProducerConsumer.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="logon();">
<mx:Script>
<![CDATA[
import mx.messaging.messages.*;
import mx.messaging.events.*;
// Subscribe to destination.
private function logon():void {
consumer.subscribe();
}
// Write received message to TextArea control.
private function messageHandler(event: MessageEvent):void {
ta.text += event.message.body + "\n";
}
// Compose the message as an instance of AsyncMessage,
// then use the Producer.send() method to send it.
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="chat"/>
<mx:Consumer id="consumer" destination="chat"
message="messageHandler(event)"/>
<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>
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/blazeds/1/blazeds_devguide/messaging_5.html