Calendar

January 2008
S M T W T F S
« Dec   Feb »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Tag Cloud

Categories

Archives

Recent Posts

Recent Comments


« Spelling Plus Library | Main | Big Announcement Coming Soon! »

More fun with AIR LocalConnection (Source Included)

By Rich Tretola | January 11, 2008
6,000 views

This sample has 2 components. The AIR portion and the Flex web portion. It allows you to drag and image into the AIR application and send it to the browser based Flex application via LocalConnection.

The AIR application accepting the image:
eflex012.jpg

The image now showing in the browser:
eflex013.jpg

Download and install this AIR application. Run the application, click the link to http://www.everythingflex.com/flex3/DropIt/Index.html to open the browser portion of the application.

As long as you have green check marks within both the AIR and Flex apps you are ready to give it a shot. Drag a small gif or jpg into the red box of the AIR application, wait a few seconds and you should get an Alert telling you to check your browser.

Here is the source (the AIR and Flex apps also have view source enabled)

AIR:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute" creationComplete="init()"
    horizontalScrollPolicy="off" verticalScrollPolicy="off"
    width="425" height="325" backgroundColor="#FFFFFF" viewSourceURL="srcview/index.html">
    <mx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.graphics.codec.JPEGEncoder;
            import mx.controls.Alert;
            import flash.net.LocalConnection;
            import flash.events.StatusEvent;

            import mx.controls.Image;
            import flash.filesystem.File;

            [Bindable]
            private var targetURL:String = "http://www.everythingflex.com/flex3/DropIt/Index.html";

            public var outbound:LocalConnection = new LocalConnection();
            public var inbound:LocalConnection = new LocalConnection();

            [Bindable]
            private var isConnected:Boolean = true;

            [Bindable]
            [Embed(source="y.gif")]
            private var yes:Class;

            [Bindable]
            [Embed(source="x.gif")]
            private var no:Class;

            private var timer:Timer;

            private var bitmapData:BitmapData;

            public function init():void{
                isConnected = false;
                outbound.addEventListener(StatusEvent.STATUS, onStatus);
                inbound = new LocalConnection();
                inbound.allowDomain('*');
                inbound.client = this;
                try {
                    inbound.connect("aircon");
                } catch (error:ArgumentError) {
                    Alert.show("Connection Failure");
                }
                timer = new Timer(1000, 0);
                timer.addEventListener("timer", timerHandler);
                timer.start();
                this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,onDragIn);
                this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,onDrop);
            }

            public function timerHandler(event:TimerEvent):void {
                outbound.send("everythingflex.com:flexcon", "testCon", outbound.domain);
            }

            public function testCon(s:String):void {
                isConnected = true;
            }

            public function getResponse(s:String):void {
                Alert.show(s,"Success");
            }

            private function onStatus(event:StatusEvent):void {
                if(event.level == "error"){
                    isConnected = false;
                } else{
                    isConnected = true;
                }
            }


            private function onDragIn(event:NativeDragEvent):void{
                NativeDragManager.acceptDragDrop(this);
            }

        private function onDrop(event:NativeDragEvent):void{
          var dropfiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
          for each (var file:File in dropfiles){
            switch (file.extension.toLowerCase()){
              case "png" :
                addImage(file.nativePath);
                break;
              case "jpg" :
                addImage(file.nativePath);
                break;
              case "jpeg" :
                addImage(file.nativePath);
                break;
              case "gif" :
                addImage(file.nativePath);
                break;
              default:
                Alert.show("Unmapped Extension");
              }
            }
          }

          private function addImage(nativePath:String):void{
            var i:Image = new Image();
            i.visible = false;
            i.addEventListener(FlexEvent.UPDATE_COMPLETE,sendJPEG);
            if(Capabilities.os.search("Mac") >= 0){
              i.source = "file://" + nativePath;
            } else {
              i.source = nativePath;
            }
            this.addChild(i);
          }

          private function sendJPEG(event:FlexEvent):void{
            try{
            var img:Image = event.target as Image;
             bitmapData = new BitmapData(img.width, img.height);
             bitmapData.draw(img);
             var bitmap:Bitmap = new Bitmap(bitmapData);
             var jpg:JPEGEncoder = new JPEGEncoder();
             var ba:ByteArray = jpg.encode(bitmapData);
             outbound.send("everythingflex.com:flexcon", "receiveImage", ba);
            } catch(e:Error){

            }
          }

          private function setVisuals(b:Boolean):Boolean{
                if(b){
                    received.source = yes;
                    message.text = "Drop a small image in the zone below";
                } else {
                    received.source = no;
                    message.text = "Make sure browser is open and pointing to:"
                }
                return b;
            }

            private function openBrowser():void{
                var url:String = targetURL;
                var urlRequest:URLRequest = new URLRequest(url);
                navigateToURL(urlRequest);
            }

        ]]>
    </mx:Script>

    <mx:Label text="Connected to Flex" x="146.5" y="282"/>
    <mx:Image id="received" x="260.5" y="282" width="16" height="18" source="{no}"/>
    <mx:Text id="message" x="10" y="10" width="403" textAlign="center" color="#000000" fontWeight="bold"/>
    <mx:LinkButton id="link" visible="{!setVisuals(isConnected)}" click="openBrowser()" label="{targetURL}" x="10" y="34" textAlign="center" width="100%"/>
    <mx:HBox id="dropzone" x="10" y="57" width="403" height="218" borderStyle="solid" borderThickness="3" borderColor="#E81414">
    </mx:HBox>

</mx:WindowedApplication>

Flex:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    creationComplete="init()" viewSourceURL="srcview/index.html">
    <mx:Script>
        <![CDATA[
            import flash.net.LocalConnection;
            import mx.controls.Alert;

            private var inbound:LocalConnection = new LocalConnection();;
            private var outbound:LocalConnection = new LocalConnection();;

            private var outboundDomain:String;

            private var timer:Timer;

            [Bindable]
            [Embed(source="y.gif")]
            private var yes:Class;

            [Bindable]
            [Embed(source="x.gif")]
            private var no:Class;

            public function init():void{
                outbound.addEventListener(StatusEvent.STATUS, onStatus);
                inbound.allowDomain('*');
                inbound.client = this;
                try {
                    inbound.connect("flexcon");
                } catch (error:ArgumentError) {
                    Alert.show("Connection failed, already in use", "Error");
                }
            }

            private function onStatus(event:StatusEvent):void {
                if(event.level == "error"){
                    received.source = no;
                } else{
                    received.source = yes;
                }
            }

            public function testCon(s:String):void{
                outboundDomain = s;
                outbound.send(outboundDomain + ":aircon", "testCon", "OK");
                timer = new Timer(1000, 0);
                timer.addEventListener("timer", timerHandler);
                timer.start();
            }

            public function timerHandler(event:TimerEvent):void {
                outbound.send(outboundDomain + ":aircon", "testCon", "OK");
            }

            public function receiveImage(ba:ByteArray):void {
                img.source = ba;
                respond();

            }

            private function respond():void {
                outbound.send(outboundDomain + ":aircon", "getResponse", 'Check you browser');
            }

        ]]>

    </mx:Script>

    <mx:Canvas horizontalCenter="0" verticalCenter="0" backgroundColor="#FFFFFF" width="100%" height="100%">
        <mx:Image id="img" x="10" y="36"/>
        <mx:Label text="Connected to AIR" x="241" y="14" color="#000000"/>
        <mx:Image id="received" x="352" y="14" width="16" height="16" source="{no}"/>
    </mx:Canvas>
</mx:Application>

Topics: ActionScript 3, Adobe AIR, Flex 3 (Moxie) | 20 Comments »

20 Responses to “More fun with AIR LocalConnection (Source Included)”

  1. Patrick Says:
    April 17th, 2008 at 2:22 pm

    Hey i bought your book. And I have qeustions… How can I drag and drop any file, not just an image and encode it as a byteArray? I see in your example, you are using a flex event, is there another way to get this data from event target, for, such as .exe, .psd etc.

    Reply to this comment

  2. everythingflex Says:
    April 17th, 2008 at 2:51 pm

    You can drag any file type into AIR, you would just need to add a new case statement to the switch in my example to handle the new file extension.

    Reply to this comment

  3. tom Says:
    April 21st, 2008 at 7:06 am

    Hi man, your AIR package is no longer supported by the new runtime, please recompile it!!

    Reply to this comment

  4. everythingflex Says:
    April 21st, 2008 at 3:48 pm

    I just uploaded a newly compiled version.

    Reply to this comment

  5. tom Says:
    April 26th, 2008 at 5:27 am

    Ok many thanks, it works very well!!!!

    Actually, I try but my published ID is not verified, so I have the felling that local connection works only if the AIR published ID is verifed?

    Did you pay a certificate for this?

    Many thanks

    Reply to this comment

  6. Chuck Freedman Says:
    April 29th, 2008 at 3:49 pm

    Rich, this is genius. What a great example of AIR! I’m curious, what led you to code this example?

    Reply to this comment

  7. everythingflex Says:
    April 29th, 2008 at 7:18 pm

    Hey Chuckstar!

    Just playing with AIR and thought why not. :-)

    I have another idea related to this sample that could actually have a business purpose.

    Reply to this comment

  8. Warren Says:
    October 23rd, 2008 at 9:58 am

    Hi there,

    I can get AS2 Flash in browser to communicate with AIR but not back again. ie I cannot get comms back from AIR to AS2 Flash in browser.

    Any suggestions please.

    Reply to this comment

  9. Warren Says:
    October 24th, 2008 at 5:17 am

    Still struggling with bi-directional AIR to AS2 LocalConnection. Any ideas out there?

    Reply to this comment

  10. hierro Says:
    November 13th, 2008 at 12:08 pm

    is there a way to connect between 2 AIR applications on same pc?

    is mandatory to have verified certificate to use localconnection ?

    nice work u did :)

    Reply to this comment

    Hugues Sansen Reply:

    try with underscored connection names:
    _myLocalConnection

    Reply to this comment

  11. Jo Says:
    February 23rd, 2009 at 7:17 am

    Hey,
    This is really awesome… I’ve got it working locally but what’s the deal with it only working with small files though?? I really need it to work for large images :( is there a file size limit?? how could I get round it??

    thanks.

    Reply to this comment

  12. Jo Says:
    February 23rd, 2009 at 8:12 am

    Hey,
    I’ve found the problem – there’s a 40K limit :(

    http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/LocalConnection.html#send()

    Reply to this comment

    Rich Tretola Reply:

    Yeah, it wasn’t meant for passing large amounts of data. More for passing text or references to data.

    Reply to this comment

  13. Edward Mansouri Says:
    June 16th, 2009 at 9:35 am

    Rich,

    This is a fantastic example and just solved a lot of my problems!

    Reply to this comment

  14. abhishek Says:
    August 25th, 2009 at 7:15 am

    hey frnds,
    can we check this code on local server ,
    I did same using Ruby On Rails, but not working for me,
    :)

    Reply to this comment

  15. Communication between application with difference browser « Flex ActionScript Guide Blog Says:
    September 21st, 2009 at 1:06 pm

    [...] http://blog.everythingflex.com/2008/01/11/more-fun-with-air-localconnection-source-included/ http://www.mail-archive.com/flexcoders@yahoogroups.com/msg119185.html [...]

  16. Patrick Says:
    February 13th, 2010 at 3:44 pm

    I’m having difficulty getting this to work, Rich. Can you please confirm this works on your end? I can’t get this working on my mac with flash10 and air 1.53.

    I am unsuccessful at making any localConnection to a flex app work. However, I can get localConnection to work with a simple .swf with a sprite inside… So this has me baffled? I wonder if it’s an issue with the flex sdk? Also, I can’t seem to get my browser flex app to talk to my air app either.

    Thanks,
    Patrick

    Reply to this comment

    Rich Tretola Reply:

    I don’t have an AIR 1.5 environment setup anymore. Does anyone else have an environment to test this in, if not I’ll recreate one?

    Reply to this comment

  17. Seb Says:
    March 7th, 2010 at 2:50 pm

    Hei , thanks for the good sample,
    but i get little problems to transfer it in my domain.

    I change the URL to something like “server.org.xyz”. I get no connection between AIR to Flex.
    (The SWF-URL is online at “http://server.org.xyz/somePath/flex.swf”.)

    The same code with a URL like “server.org” or “server.de” has no problems. It’s possible, that URLs with more than one point a generall problem in this sample-code?

    Thanks
    Seb

    Reply to this comment

Comments