Several Customers in the Early Adopter Program have asked me if two Flex applications running on the same machine can communicate with each other. The answer is yes: the LocalConnection class allows a Flex application to send data to- and trigger events in another Flex application running on the same machine. Here is a simple example:
1. "Sending" Application (Run it!)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" initialize="initialize()">
<mx:Script>
var myConnection;
function initialize() {
myConnection = new LocalConnection();
myConnection.onStatus = mx.utils.Delegate.create(this, onStatus);
}
function sendMessage() {
myConnection.send("application_b", "messagePosted", myMessage.text);
}
function onStatus(result) {
status.text=result.level == "error"?"Operation failed":"Operation succeeded";
}
</mx:Script>
<mx:TextInput id="myMessage" />
<mx:Button click="sendMessage()" label="Send"/>
<mx:Label id="status"/>
</mx:Application>
Code highlights:
- myConnection = new LocalConnection();
Create an instance of the LocalConnection class
- myConnection.onStatus = mx.utils.Delegate.create(this, onStatus);
The onStatus event is triggered after the send() method is invoked to allow you to respond to the success or failure of the operation
- myConnection.send("receivingapp", "messagePosted", myMessage.text);
"reveivingapp" is the name the receiving app used to connect
"messagePosted" is the event to trigger in the receiving application
myMessage.text is the data to pass to the receiving application. You can pass objects or multiple comma-separated values.
2. "Receiving" Application ( Run it!)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" initialize="initialize()">
<mx:Script>
var myConnection;
function initialize() {
myConnection = new LocalConnection();
myConnection.messagePosted = mx.utils.Delegate.create(this, messagePosted);
myConnection.connect("receivingapp");
}
function messagePosted(message) {
messageList.text+=message+"/n";
}
</mx:Script>
<mx:TextArea id="messageList" width="300" height="300"/>
</mx:Application>
Code Highlights
- myConnection = new LocalConnection();
Create an instance of the LocalConnection class
- myConnection.messagePosted = mx.utils.Delegate.create(this, messagePosted);
Delegate messagePosted to the messagePosted function
- myConnection.connect("receivingapp");
Connect using "receivingapp" as the connection name