Jump to content

tcp comunication between autoit and android


 Share

Recommended Posts

hello, im having troube sending messages to android over tcp, right now autoit is acting as a server, and android as a client, i can send data from adroid to autoit over tcp but not from autoit to android, here is the full code i have been using, but my main goal is in Func MyTCP_Server($sIPAddress, $iPort) and i dont know why tcpsend doesnt work :S

by the way when i tried 2 androids server and clients they work fine, so i think its not a problem with my android code

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

Example()

Func Example()
    TCPStartup() ; Start the TCP service.

    ; Register OnAutoItExit to be called when the script is closed.
    OnAutoItExitRegister("OnAutoItExit")

    ; Assign Local variables the loopback IP Address and the Port.
    Local $sIPAddress = "10.121.119.64" ; This IP Address only works for testing on your own computer.
    Local $iPort = 65432 ; Port used for the connection.

    #Region GUI
    Local $sTitle = "TCP Start"
    Local $hGUI = GUICreate($sTitle, 250, 70)

    Local $idBtnServer = GUICtrlCreateButton("1. Server", 65, 10, 130, 22)

    Local $idBtnClient = GUICtrlCreateButton("2. Client", 65, 40, 130, 22)

    GUISetState(@SW_SHOW, $hGUI)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
            Case $idBtnServer
                WinSetTitle($sTitle, "", "TCP Server started")
                GUICtrlSetState($idBtnClient, $GUI_HIDE)
                GUICtrlSetState($idBtnServer, $GUI_DISABLE)
                If Not MyTCP_Server($sIPAddress, $iPort) Then ExitLoop
            Case $idBtnClient
                WinSetTitle($sTitle, "", "TCP Client started")
                GUICtrlSetState($idBtnServer, $GUI_HIDE)
                GUICtrlSetState($idBtnClient, $GUI_DISABLE)
                If Not MyTCP_Client($sIPAddress, $iPort) Then ExitLoop
        EndSwitch

        Sleep(10)
    WEnd

    #EndRegion GUI
EndFunc   ;==>Example

Func MyTCP_Server($sIPAddress, $iPort)


    ; Assign a Local variable the socket and bind to the IP Address and Port specified with a maximum of 100 pending connexions.
    Local $iListenSocket = TCPListen($sIPAddress, $iPort, 100)
    Local $iError = 0

    If @error Then
        ; Someone is probably already listening on this IP Address and Port (script already running?).
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Server:" & @CRLF & "Could not listen, Error code: " & $iError)
        Return False
    EndIf


    Local $iSocket = 0

While 1

    Do ; Wait for someone to connect (Unlimited).
        ; Accept incomming connexions if present (Socket to close when finished; one socket per client).
        $iSocket = TCPAccept($iListenSocket)

        ; If an error occurred display the error code and return False.
        If @error Then
            $iError = @error
            MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Server:" & @CRLF & "Could not accept the incoming connection, Error code: " & $iError)
            Return False
        EndIf

        If GUIGetMsg() = $GUI_EVENT_CLOSE Then Return False
    Until $iSocket <> -1 ;if different from -1 a client is connected.

;I WANT TO SEND HI TO ANDROID HERE
    TCPSend ($iSocket, "Hi")

    ; Close the Listening socket to allow afterward binds.
    ;TCPCloseSocket($iListenSocket)

    ; Assign a Local variable the data received.
    Local $sReceived = TCPRecv($iSocket, 4) ;we're waiting for the string "tata" OR "toto" (example script TCPRecv): 4 bytes length.

    ; Notes: If you don't know how much length will be the data,
    ; use e.g: 2048 for maxlen parameter and call the function until the it returns nothing/error.

    ; Display the string received.
    MsgBox($MB_SYSTEMMODAL, "", "Server:" & @CRLF & "Received: " & $sReceived)

    ; Close the socket.
    ;TCPCloseSocket($iSocket)

WEnd

EndFunc   ;==>MyTCP_Server

Func MyTCP_Client($sIPAddress, $iPort)
    ; Assign a Local variable the socket and connect to a listening socket with the IP Address and Port specified.
    Local $iSocket = TCPConnect($sIPAddress, $iPort)
    Local $iError = 0

    ; If an error occurred display the error code and return False.
    If @error Then
        ; The server is probably offline/port is not opened on the server.
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not connect, Error code: " & $iError)
        Return False
    EndIf

    ; Send the string "tata" to the server.
    TCPSend($iSocket, "tata")

    ; If an error occurred display the error code and return False.
    If @error Then
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not send the data, Error code: " & $iError)
        Return False
    EndIf

    ; Close the socket.
    TCPCloseSocket($iSocket)
EndFunc   ;==>MyTCP_Client



Func OnAutoItExit()
    TCPShutdown() ; Close the TCP service.
EndFunc   ;==>OnAutoItExit

and here is my android where it receives data yust in case

while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");

 

Link to comment
Share on other sites

Assuming you are using a current version of AutoIt...

Better said, that not -- the helpfile example needs some help.

Your script, in function MyTCP_Server, needs to check for an error under TCPSend().
Whats the error code?

Also, TCPRecv will usually miss on the first call, so you'll need to set up something like
a FOR loop with a count of maybe 25 with a Stringlen check greater than zero, and a
sleep(10) at the bottom of that loop, so it doesn't go so fast.

Also, a TCPSend followed immediately by a TCPCloseSocket will might result
in a error code of 10053 on the other side. A Sleep(1000) is needed between
those two to prevent this.

The TCPRecv bytes length of 4 is an example, and needs to be changed to
1024 or higher, if you plan on using any kind of real communications.

Also, you need to insert Opt('TCPTimeout', 1000) at the top of your script.
Otherwise, the default 100ms will most likely not be enough time to connect.

I'm telling all you this, because I have already fixed your script, and this is what
I had to do to make it work reliably.

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

hello, thanks for your help, but i still cant make it to receive the message. Here is the updated code

 

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

Opt('TCPTimeout', 1000)

; Start First clicking on "1. Server"
; Then start a second instance of the script selecting "2. Client"

Example()

Func Example()
    TCPStartup() ; Start the TCP service.

    ; Register OnAutoItExit to be called when the script is closed.
    OnAutoItExitRegister("OnAutoItExit")

    ; Assign Local variables the loopback IP Address and the Port.
    Local $sIPAddress = "10.121.119.64" ; This IP Address only works for testing on your own computer.
    Local $iPort = 65432 ; Port used for the connection.

    #Region GUI
    Local $sTitle = "TCP Start"
    Local $hGUI = GUICreate($sTitle, 250, 70)

    Local $idBtnServer = GUICtrlCreateButton("1. Server", 65, 10, 130, 22)

    Local $idBtnClient = GUICtrlCreateButton("2. Client", 65, 40, 130, 22)

    GUISetState(@SW_SHOW, $hGUI)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
            Case $idBtnServer
                WinSetTitle($sTitle, "", "TCP Server started")
                GUICtrlSetState($idBtnClient, $GUI_HIDE)
                GUICtrlSetState($idBtnServer, $GUI_DISABLE)
                If Not MyTCP_Server($sIPAddress, $iPort) Then ExitLoop
            Case $idBtnClient
                WinSetTitle($sTitle, "", "TCP Client started")
                GUICtrlSetState($idBtnServer, $GUI_HIDE)
                GUICtrlSetState($idBtnClient, $GUI_DISABLE)
                If Not MyTCP_Client($sIPAddress, $iPort) Then ExitLoop
        EndSwitch

        Sleep(10)
    WEnd

    #EndRegion GUI
EndFunc   ;==>Example

Func MyTCP_Server($sIPAddress, $iPort)


    ; Assign a Local variable the socket and bind to the IP Address and Port specified with a maximum of 100 pending connexions.
    Local $iListenSocket = TCPListen($sIPAddress, $iPort, 100)
    Local $iError = 0

    If @error Then
        ; Someone is probably already listening on this IP Address and Port (script already running?).
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Server:" & @CRLF & "Could not listen, Error code: " & $iError)
        Return False
    EndIf

    Local $iSocket = 0

While 1
    ; Assign a Local variable to be used by the Client socket.

    Do ; Wait for someone to connect (Unlimited).
        ; Accept incomming connexions if present (Socket to close when finished; one socket per client).
        $iSocket = TCPAccept($iListenSocket)

        ; If an error occurred display the error code and return False.
        If @error Then
            $iError = @error
            MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Server:" & @CRLF & "Could not accept the incoming connection, Error code: " & $iError)
            Return False
        EndIf

        If GUIGetMsg() = $GUI_EVENT_CLOSE Then Return False
    Until $iSocket <> -1 ;if different from -1 a client is connected.

    TCPSend ($iSocket, "Hi")
    If @error Then
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not send the data, Error code: " & $iError)
        Return False
    EndIf


    ; Close the Listening socket to allow afterward binds.
    ;TCPCloseSocket($iListenSocket)

    ; Assign a Local variable the data received.
    Local $sReceived = TCPRecv($iSocket, 1024) ;we're waiting for the string "tata" OR "toto" (example script TCPRecv): 4 bytes length.

    ; Notes: If you don't know how much length will be the data,
    ; use e.g: 2048 for maxlen parameter and call the function until the it returns nothing/error.

    ; Display the string received.
    MsgBox($MB_SYSTEMMODAL, "", "Server:" & @CRLF & "Received: " & $sReceived)

    ; Close the socket.
    Sleep(1000)
    ;TCPCloseSocket($iSocket)

WEnd

EndFunc   ;==>MyTCP_Server



Func MyTCP_Client($sIPAddress, $iPort)
    ; Assign a Local variable the socket and connect to a listening socket with the IP Address and Port specified.
    Local $iSocket = TCPConnect($sIPAddress, $iPort)
    Local $iError = 0

    ; If an error occurred display the error code and return False.
    If @error Then
        ; The server is probably offline/port is not opened on the server.
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not connect, Error code: " & $iError)
        Return False
    EndIf

    ; Send the string "tata" to the server.
    TCPSend($iSocket, "tata")

    ; If an error occurred display the error code and return False.
    If @error Then
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not send the data, Error code: " & $iError)
        Return False
    EndIf

    ; Close the socket.
    TCPCloseSocket($iSocket)
EndFunc   ;==>MyTCP_Client



Func OnAutoItExit()
    TCPShutdown() ; Close the TCP service.
EndFunc   ;==>OnAutoItExit

 

Link to comment
Share on other sites

seres,

Perhaps there is a better way, if you were to explain step by step what you want accomplished.
There are many ways to configure a script like that, and I'm not sure what you're trying to do,
or what you expect of each side.

You said, "I WANT TO SEND HI TO ANDROID HERE".

Surely you want to do more than send "HI" ???

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

Here's a solution on the newsgroups that posted today.
File transfer via local web page over wifi...

https://play.google.com/store/apps/details?id=com.smarterdroid.wififiletransfer&hl=en_GB

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

On 17/3/2017 at 11:43 PM, ripdad said:

seres,

Perhaps there is a better way, if you were to explain step by step what you want accomplished.
There are many ways to configure a script like that, and I'm not sure what you're trying to do,
or what you expect of each side.

You said, "I WANT TO SEND HI TO ANDROID HERE".

Surely you want to do more than send "HI" ???
 

hello, what i want is to share the mouse from my computer to my android, and to send other commands like volume power, etc.

I figure that i need something faster than adb to manage mouse manipulation. If im able to send data(HI), it will be the mouse coordinates(X,Y), i have been reading about jason, but im not sure wich way is better and faster.

Link to comment
Share on other sites

On 17/3/2017 at 8:24 AM, ripdad said:

Assuming you are using a current version of AutoIt...

 

i found something that might be the problem, and it is in the way the data is manipulated, here is the code that the client uses

this is to send data

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024];

this is to get data

while ((bytesRead = inputStream.read(buffer)) != -1) {
   byteArrayOutputStream.write(buffer, 0, bytesRead);
   response += byteArrayOutputStream.toString("UTF-8");

and here is how android server sends the data

OutputStream outputStream;
            String msgReply = "Hello from Server, you are #" + cnt;

            try {
                outputStream = hostThreadSocket.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                printStream.print(msgReply);
                printStream.close();

maybe in autoit im not sending it right because the app get stuck in this part and it never  receive the data

Edited by seres
addition
Link to comment
Share on other sites

What, if any, is the error code from TCPSend?

How do you plan to control the mouse on your Android through TCP?

What language are you using on the Android? Javascript?

Edited by ripdad

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

2 hours ago, ripdad said:

What, if any, is the error code from TCPSend?

How do you plan to control the mouse on your Android through TCP?

What language are you using on the Android? Javascript?
 

1. none, i have the code to show me an error, but no error is given, and in the android it yust go the while waiting for data

2. there are file in android that manage the mouse and other devices, because my phone is rooted i plan to manipulate those files to move the mouse

3. im using android studio( Java )

Link to comment
Share on other sites

Okay, now that I get the scope of what you're doing, lets try a simple and tested code.
If this doesn't work, then it's something on the Android side.

Or, we may have to adjust the script if the Android won't accept incoming connections.

Make sure I.P. and Port numbers are correct.

BTW, I don't have an Android so I tested on localhost 127.0.0.1
That doesn't matter, it should work either way.

 

Opt('MustDeclareVars', 1)
Opt('TCPTimeout', 1000)
;
If Not TCPStartup() Then
    Exit MsgBox(0, 'AutoIt', 'Error: TCPStartup' & @TAB, 10)
EndIf
;
_TCPSend('AutoIt Test String', '127.0.0.1', 65432)
;
Func _TCPSend($sData, $sIp, $nPort)
    Local $nSocket = TCPConnect($sIp, $nPort)
    Local $nError = @error; <-- if error code = 10060, then timed out
    If $nError Or $nSocket < 1 Then
        MsgBox(0, 'AutoIt', 'TCPConnect Error: ' & $nError)
        Return
    EndIf
    ;
    TCPSend($nSocket, $sData)
    $nError = @error
    If $nError Then
        MsgBox(0, 'AutoIt', 'TCPSend Error: ' & $nError)
    EndIf
    ;
    Sleep(1000)
    TCPCloseSocket($nSocket)
EndFunc
;

 

Edited by ripdad
adjusted silly forum formatting

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

39 minutes ago, ripdad said:

Okay, now that I get the scope of what you're doing, lets try a simple and tested code.
If this doesn't work, then it's something on the Android side.

Make sure I.P. and Port numbers are correct.

BTW, I don't have an Android so I tested on localhost 127.0.0.1
That doesn't matter, it should work either way.
 

Opt('MustDeclareVars', 1)
Opt('TCPTimeout', 1000)
;
If Not TCPStartup() Then
    Exit MsgBox(0, 'AutoIt', 'Error: TCPStartup' & @TAB, 10)
EndIf
;
_TCPSend('AutoIt Test String', '10.121.119.64', 65432)
;
Func _TCPSend($sData, $sIp, $nPort)
    Local $nSocket = TCPConnect($sIp, $nPort)
    Local $nError = @error; <-- if $nError = 10060, then timed out
    If $nError Or $nSocket < 1 Then
        MsgBox(0, 'AutoIt', 'TCPConnect Error: ' & $nError)
        Return
    EndIf
    ;
    TCPSend($nSocket, $sData)
    $nError = @error
    If $nError Then
        MsgBox(0, 'AutoIt', 'TCPSend Error: ' & $nError)
    EndIf
    ;
    Sleep(1000)
    TCPCloseSocket($nSocket)
EndFunc
;

 

Not exactly because i want the computer to act as a server.

The computer waits for connection, then after it gets a connection it sends data back to the connected android.

It works well untill it sends the data, for some reason android doent recognize that data. But when i do it via android to android it works, the only difference i see is that the android that act as a server uses hostThreadSocket

Here is cleaner example i found that is what i think should work

Global $MainSocket = -1
Global $ConnectedSocket = -1
Local $MaxConnection = 1; Maximum Amount Of Concurrent Connections
Local $MaxLength = 512; Maximum Length Of String
;~ Local $Port = 1000; Port Number
;~ Local $Server = @IPAddress1; Server IpAddress

Local $Server = "10.121.119.64" ; This IP Address only works for testing on your own computer.
Local $Port = 65432 ; Port used for the connection.
TCPStartup()
$MainSocket = TCPListen($Server, $Port)
If $MainSocket = -1 Then Exit MsgBox(16, "Error", "Unable to intialize socket.")
While 1
    $Data = TCPRecv($ConnectedSocket, $MaxLength)
    If $Data = "~bye" Then
        MsgBox(16, "Session Ended", "Connection Terminated.")
        Exit
    ElseIf $Data <> "" Then
; Unconditional Receive
        MsgBox(0, "Received Packet", $Data)
    EndIf
    If $ConnectedSocket = -1 Then
;~      MsgBox(0,"1", "$ConnectedSocket = -1")
        $ConnectedSocket = TCPAccept($MainSocket)
        If $ConnectedSocket <> -1 Then
; Someone Connected
            MsgBox(0,"2", "send Connected")
            TCPSend($ConnectedSocket, "Connected!")
        EndIf
    EndIf
WEnd
Func OnAutoItExit()
    If $ConnectedSocket <> - 1 Then
        TCPSend($ConnectedSocket, "~bye")
        TCPCloseSocket($ConnectedSocket)
    EndIf
    If $MainSocket <> -1 Then TCPCloseSocket($MainSocket)
    TCPShutdown()
EndFunc;==>OnAutoItExit

 

Link to comment
Share on other sites

Tested with script in post #11

OnAutoItExitRegister('OnAutoItExit')
Opt('MustDeclareVars', 1)
;
If Not TCPStartup() Then
    Exit MsgBox(0, 'AutoIt', 'Error: TCPStartup' & @TAB, 10)
EndIf
;
Local $MaxConnections = 1
Local $MaxLength = 512
Local $Server = '10.121.119.64'
Local $Port = 65432
Local $sData, $nError
;
Global $ConnectedSocket
Global $MainSocket = TCPListen($Server, $Port, $MaxConnections)
If $MainSocket < 1 Then
    Exit MsgBox(16, 'Error', 'Unable to intialize socket')
EndIf
;
While 1
    Do
        Sleep(100)
        $ConnectedSocket = TCPAccept($MainSocket)
    Until $ConnectedSocket > 0
    ;
    TCPSend($ConnectedSocket, 'Connected!')
    $nError = @error
    If $nError Then
        MsgBox(0, 'TCPSend Error', 'Error Code: ' & $nError)
        ContinueLoop
    EndIf
    ;
    For $i = 1 To 100
        $sData = TCPRecv($ConnectedSocket, $MaxLength)
        $nError = @error
        If $nError Then
            MsgBox(16, 'TCPRecv Error', 'Error Code: ' & $nError)
            ExitLoop
        EndIf
        ;
        If $sData <> '' Then
            If $sData = '~bye' Then
                MsgBox(16, 'Session Ended', 'Connection Terminated')
                Exit
            Else
                MsgBox(0, 'Received Packet', $sData)
                ExitLoop
            EndIf
        EndIf
        Sleep(10)
    Next
    ;
    TCPCloseSocket($ConnectedSocket)
    If $i >= 100 Then
        MsgBox(0, 'TCPRecv', 'Timed Out!')
    EndIf
WEnd
;
Func OnAutoItExit()
    If $ConnectedSocket > 0 Then
        TCPSend($ConnectedSocket, '~bye')
        TCPCloseSocket($ConnectedSocket)
    EndIf
    TCPCloseSocket($MainSocket)
    TCPShutdown()
EndFunc
;

 

Edited by ripdad

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

12 hours ago, ripdad said:

Tested with script in post #11

OnAutoItExitRegister('OnAutoItExit')
Opt('MustDeclareVars', 1)
;
If Not TCPStartup() Then
    Exit MsgBox(0, 'AutoIt', 'Error: TCPStartup' & @TAB, 10)
EndIf
;
Local $MaxConnections = 1
Local $MaxLength = 512
Local $Server = '10.121.119.64'
Local $Port = 65432
Local $sData, $nError
;
Global $ConnectedSocket
Global $MainSocket = TCPListen($Server, $Port, $MaxConnections)
If $MainSocket < 1 Then
    Exit MsgBox(16, 'Error', 'Unable to intialize socket')
EndIf
;
While 1
    Do
        Sleep(100)
        $ConnectedSocket = TCPAccept($MainSocket)
    Until $ConnectedSocket > 0
    ;
    TCPSend($ConnectedSocket, 'Connected!')
    $nError = @error
    If $nError Then
        MsgBox(0, 'TCPSend Error', 'Error Code: ' & $nError)
        ContinueLoop
    EndIf
    ;
    For $i = 1 To 100
        $sData = TCPRecv($ConnectedSocket, $MaxLength)
        $nError = @error
        If $nError Then
            MsgBox(16, 'TCPRecv Error', 'Error Code: ' & $nError)
            ExitLoop
        EndIf
        ;
        If $sData <> '' Then
            If $sData = '~bye' Then
                MsgBox(16, 'Session Ended', 'Connection Terminated')
                Exit
            Else
                MsgBox(0, 'Received Packet', $sData)
                ExitLoop
            EndIf
        EndIf
        Sleep(10)
    Next
    ;
    TCPCloseSocket($ConnectedSocket)
    If $i >= 100 Then
        MsgBox(0, 'TCPRecv', 'Timed Out!')
    EndIf
WEnd
;
Func OnAutoItExit()
    If $ConnectedSocket > 0 Then
        TCPSend($ConnectedSocket, '~bye')
        TCPCloseSocket($ConnectedSocket)
    EndIf
    TCPCloseSocket($MainSocket)
    TCPShutdown()
EndFunc
;

 

WOOOWWW Amazing O.O thank you very much thats what i was looking for :D

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...