3.03.2010

AS3 Tips of the Day - LocalConnection AS3

AS3' LocalConnection is just the same as in AS2, only differences is the event listeners. This can be useful when it needs to communicate a AS2 to AS3, because we can't loadmovie a AS2 to AS3, or vice versa. There are other ways to use this. Hope my simple example can help others.

Sender:

package {
import flash.display.*;
import flash.events.*;
import flash.net.*;

public class Sender extends MovieClip {
private var send_lc:LocalConnection;
private var params:String = "my name is mykhel";
public function Sender():void {
/// instantiate send_lc
send_lc = new LocalConnection();

/// should have status event for testing purposes
send_lc.addEventListener(StatusEvent.STATUS, onStatus);

/// send to receiver a connection id and methods with params
/// .toString() just to make sure the receiver will be accepting a String
send_lc.send("connectId", "callBackFunction", params.toString());
}

/// instantiate rcv_lc
private function onStatus(evt:*):void {
switch (evt.level) {
case "status":
trace("LocalConnection.send() succeeded");
break;
case "error":
trace("LocalConnection.send() failed");
break;
}
}
}
}


Receiver:

package {
import flash.display.*;
import flash.events.*;
import flash.net.*;

public class Receiver extends MovieClip {
private var rcv_lc:LocalConnection;
public function Receiver():void {
/// instantiate rcv_lc
rcv_lc = new LocalConnection();

/// setting rcv_lc client to this
rcv_lc.client = this;

/// i put in a enterframe event the connect, i used this in a tandem simultaneous connect
addEventListener(Event.ENTER_FRAME, function ():void {
try {

/// rcv_lc connect with connectId (this should be unique id)
rcv_lc.connect("connecId");

} catch (error:ArgumentError) {
trace("Can't connect...the connection name is already being used by another SWF");
}
});
}

/// function to be execute passed from LC sender.
public function changeImage(str:String):void {
trace("LC CONNECTED. PARAMS: " + str);
}
}
}

No comments:

Post a Comment