---
title: "as3 swf间通讯——LocalConnection"
author: "wdbk123"
date: "2012-04-20T18:06:20Z"
tags: []
categories: ["Web前端"]
slug: "as3-swf-localconnection"
draft: false
lastmod: "2012-04-20T18:06:20Z"
id: 1491697
url: "https://wdbk123.iteye.com/blog/1491697"
---

解决两个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那里取了个随机数，来对不同浏览器页面设置不同的连接名，避免同名连接干扰...