使用本地连接在AIR应用程序之间发送文件

时间:2011-02-02 06:27:52

标签: flex air flashbuilder4

如何使用本地连接在空中应用程序之间发送文本文件?

Sender AIR

private var conn:LocalConnection;

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

            private function Sender():void {

                var alphabets:File= File.createTempFile();
                var file:FileStream = new FileStream();
                file.open(alphabets,FileMode.WRITE);
                file.writeUTFBytes("Have a nice day");      
                file.close();
                conn.send("app#ReceiverAIR:MyConnection", "lcHandler",t1.text,alphabets);
            }

            private function onStatus(event:StatusEvent):void {
                switch (event.level) {
                    case "status":
                        trace("LocalConnection.send() succeeded");
                        break;
                    case "error":
                        trace("LocalConnection.send() failed");
                        break;
                }
            }           

    ]]>
</fx:Script>



<mx:TextArea id="t1" />
<mx:Button id="b1" label="Send" click="Sender()" />

Receiver AIR

import flash.net.LocalConnection;

        import mx.collections.ArrayCollection;

        private var conn:LocalConnection;

        public function LocalConnectionReceiverExample()     {

            conn = new LocalConnection();
            conn.client = this;
            try {
                conn.allowDomain('app#SenderAIR');
                conn.connect("MyConnection");

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

        public function lcHandler(msg:String,myfile:File):void {
            trace("i am in lcHandler");
            t1.text=msg;    
        }

    ]]>
</fx:Script>

<mx:TextArea id="t1" editable="false"/>

它出现以下错误

Error #2044: Unhandled AsyncErrorEvent:. text=Error #2095: 
flash.net.LocalConnection was unable to invoke callback lcHandler. 
error=TypeError: Error #1034: 
Type Coercion failed: 
cannot convert Object@83d6791 to flash.filesystem.File.

2 个答案:

答案 0 :(得分:2)

编辑以反映OP的更改

感谢您的更新。据我所知,您通过LocalConnection发送的所有对象必须符合以下规定:

  1. 必须使用AMF序列化
  2. 序列化数据不得超过40K
  3. 我猜这个文件不是可序列化的类型。

    要尝试的事情:

    1. 注册别名。双方都运行flash.net.registerClassAlias('FileAlias', File)
    2. 发送更原始的数据类型。改为发送文件名或文件数据?
    3. 祝你好运! 布莱恩

答案 1 :(得分:0)

你不能以这种方式发送文件...我最终创建了一个字节数组并将字节数组发送到接收器。然后我将字节数组复制到接收器的文件中。