mardi 27 septembre 2016

How to connect to a TCP server from an AIR Android App?

I am working on a Home Automation system using the ESP8266 device. I build a simple program on AIR Desktop to connect to the ESP8266 and send strings to it. Here is the code:

package 
{ 
   import flash.display.Sprite; 
   import flash.events.Event; 
   import flash.events.IOErrorEvent; 
   import flash.events.ProgressEvent; 
   import flash.events.ServerSocketConnectEvent; 
   import flash.net.ServerSocket; 
   import flash.net.Socket; 
   import flash.events.MouseEvent;
   import flash.utils.ByteArray;
   import flash.security.*;

  public class main extends Sprite 
 { 
    private var serverURL:String; 
    private var portNumber:int; 
    private var socket:Socket; 
    private var state:int = 0;
    private var msg:ByteArray;

    public function main() 
    { 

        send_btn.addEventListener(MouseEvent.CLICK, onSendMessage, false, 0, true);
        Telnet("192.168.0.113", 90)

    } 

    public function Telnet(server:String, port:int) 
    { 
        serverURL = server; 
        portNumber = port; 
        socket = new Socket(); 
        socket.addEventListener(Event.CONNECT, connectHandler); 

        //socket.addEventListener(ProgressEvent.SOCKET_DATA, dataHandler); 
        ///Security.loadPolicyFile("http://" + serverURL + "/crossdomain.xml"); 
        try 
        { 
            trace("Trying to connect to " + serverURL + ":" + portNumber + "\n"); 
            socket.connect(serverURL, portNumber); 
        } 
        catch (error:Error) 
        { 
            trace(error.message + "\n"); 
            socket.close(); 
        } 
    }

    public function connectHandler(e:Event):void
    {
        trace("Connected Successfuly.");
    }

    public function writeBytesToSocket(ba:ByteArray):void 
    { 

        socket.writeBytes(ba); 
        socket.flush(); 
    }



    private function onSendMessage(e:MouseEvent):void
    {
        msg = new ByteArray();
        msg.writeUTFBytes(msg_txt.text);
        writeBytesToSocket(msg);

    }
 }
}

While running the project on my Laptop, everything works fine. I can connect the device and send strings as well. Then I published as an AIR Android project and installed the apk on BlueStacks, it still worked as expected. But when I installed the apk on my android phone, it doesn't seem to work.

Any help is greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire