as3 swf间通讯——LocalConnection
解决两个swf间通讯的问题,
例子:
A.swf源码:
package {
?import flash.display.MovieClip;
?import flash.external.ExternalInterface;
?import flash.system.Security;
?import flash.net.LocalConnection;
?import flash.events.Event;
?import flash.events.StatusEvent;
?import flash.display.StageQuality;
?public class a extends MovieClip {
??var con:LocalConnection;
??var id:Number;
??public function a() {
???stage.quality=StageQuality.MEDIUM;
???Security.allowDomain('*');
???init();
??}
??function init():void {
???con = new LocalConnection();
???con.addEventListener(StatusEvent.STATUS, onStatus);
???if (loaderInfo.parameters["f"]==null) {
????id=10;
???} else {
????id=loaderInfo.parameters["f"];
???}
???this.addEventListener(Event.ENTER_FRAME,onEventFrameHandler);
??}
??function onEventFrameHandler(evt:Event):void {
???txt.text=currentFrame.toString()+ " = lc_name"+id;
???if ((currentFrame==1) || (currentFrame==51) || (currentFrame==101) || (currentFrame==151) || (currentFrame==201)) {
????con.send("lc_name"+id, "lcHandler",currentFrame.toString());
???}
???
??}
??function onStatus(event:StatusEvent):void {
???switch (event.level) {
????case "status" :
?????//trace("LocalConnection.send() succeeded");
?????break;
????case "error" :
?????//trace("LocalConnection.send() failed");
?????break;
???}
??}
?}
}
?
B.swf源码:
package {
?import flash.external.ExternalInterface;
?import flash.system.Security;
?import flash.net.LocalConnection;
?import flash.events.Event;
?import flash.events.StatusEvent;
?import flash.display.MovieClip;
?import flash.display.StageQuality;
?public class b extends MovieClip {
??var id:Number;
??private var con:LocalConnection;
??public function b() {
???//stop();
???stage.quality=StageQuality.MEDIUM;
???Security.allowDomain('*');
???init();
???this.addEventListener(Event.ENTER_FRAME,onEventFrameHandler);
??}
??function init():void {
???con = new LocalConnection();
???con.client=this;
???if (loaderInfo.parameters["f"]==null) {
????id=10;
???} else {
????id=loaderInfo.parameters["f"];
???}
???try {
????con.connect("lc_name"+id);
???} catch (error:ArgumentError) {
????txt.text="Can't connect...the connection name is already being used by another SWF";
???}
??}
??public function lcHandler(val:Number):void {
???this.gotoAndPlay(val+1);
???//txt.text='- : '+val;
??}
??function onEventFrameHandler(evt:Event):void {
???txt.text=currentFrame.toString()+' = '+ "lc_name"+id;
??}
?}
}
?
?
注:
? 为了避免在多个浏览器上面查看页面效果时,两个swf连接之间的干扰,此例中的:loaderInfo.parameters["f"],是从js那里取了个随机数,来对不同浏览器页面设置不同的连接名,避免同名连接干扰...