利用LocalConnection实现多个应用之间的通讯 (不同MXML之间的通信)

当我们需要在两个不同的Flex Application之间进行一些数据交换时,有什么办法进行通讯呢,flash本身就提供了一套API(LocalConnection)。这里我们简单讲讲如何使用LocalConnection进行两个应用之间数据交互。

首先看看LocalConnection对象有哪些主要的method:

addEventListener() : 通常建立一个对status的Listener,随时观察connection的状态

allDomain() :允许不同domain之间的应用进行通讯, 这个跟安全有关,默认是不允许的

allowInsecureDomain() :同allDomain,但是它需要的安全性低一些,允许非Https的

close() :关闭连接

connect(connectionName:String) :建立连接,并指定连接名

send(connectionName:String, methodName:String,...rest):发送数据,目的地为connectionName,调用的是该App的methodName

下面直接看例子代码:

//LocalApp_Send.mxml    - 主应用程序,消息发起程序

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark" 
  xmlns:mx="library://ns.adobe.com/flex/mx" 
  minWidth="955" minHeight="600"
  initialize="init()">

<fx:Script>
private var myConnection:LocalConnection;

private function init() :void{
myConnection = new LocalConnection();
myConnection.addEventListener(StatusEvent.STATUS, onStatus);
}

private function sendMessage() : void{
//call the receive app's method 'callFunc' to send the text
myConnection.send("receivingapp", "callFunc", myMessage.text);
}

private function onStatus(result:StatusEvent) :void{
status.text=result.level == "error"?"Operation failed":"Operation succeeded";

</fx:Script>

<s:TextInput id="myMessage" x="10" y="10" />
<s:Button click="sendMessage()" label="Send" x="200" y="10"/>
<s:Label id="status" x="50" y="50"/>

</s:Application>

//LocalApp_Receive.mxml - 消息接收程序

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark" 
  xmlns:mx="library://ns.adobe.com/flex/mx"
  minWidth="955" minHeight="600"
  initialize="init()">

<fx:Script>
private var myConnection : LocalConnection;
private function init() :void{
myConnection = new LocalConnection();
myConnection.client=this;//specify this app as LocalConnection's callback object
myConnection.connect("receivingapp");

public function callFunc(message:String=""):void {
messageList.text+=message+"\n";
}
</fx:Script>

<s:TextArea id="messageList" width="300" height="300" x="10" y="30"/>

</s:Application>

 其中

App_Send

myConnection.addEventListener(StatusEvent.STATUS, onStatus);

     建立连接的状态Listener

myConnection.send("receivingapp""callFunc", myMessage.text);

     发送消息内容myMessage.text到receivingapp中,调用的函数名为callFunc

App_Receive

myConnection.client=this;//specify this app as LocalConnection's callback object

myConnection.connect("receivingapp");

    指定myConnection的client为当前应用,并以receivingapp的名字建立连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值