Jump to content

Autoit-Socket-IO - Networking in AutoIt made simple!


Recommended Posts

Nice job, thanks! Very useful in a project I did recently.

One note: in function __Io_Init() which itself is called by _Io_Listen() the the TCP timeout is set to 5 msec. This is somewhat short, even on a busy LAN. My application sometimes would return a error when calling _Io_Listen() at startup (with @extended set to 10060). Raising this value fixed the problem.

Just in case someone runs into the same problem.

Link to post
Share on other sites
  • Replies 60
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Popular Posts

Version 2.x.x and 3.x.x has been moved to branch 3.x About Autoit-Socket-IO Autoit-Socket-IO is a event driven TCP/IP wrapper heavily inspired from Socket.IO with focus on user friendliness

Hello. I am not dead! I suggest that everyone that uses this UDF in production, updates to this version. Version 1.5.0 (This update DOES NOT break scripts) Added AutoIt like docs under

What maybe would work too is to $nPing = ping() the server right before TCPConnect and setting this $nPing, if not unusally high, as the current tcptimeout. Then connect. And after success reseting th

On 2018-02-03 at 6:54 PM, autoitter said:

Nice job, thanks! Very useful in a project I did recently.

One note: in function __Io_Init() which itself is called by _Io_Listen() the the TCP timeout is set to 5 msec. This is somewhat short, even on a busy LAN. My application sometimes would return a error when calling _Io_Listen() at startup (with @extended set to 10060). Raising this value fixed the problem.

Just in case someone runs into the same problem.

Hi and thanks for the input.

The reason is behind why the TCPTimeout is set to 10 is because

Quote

TCPSend speed is about 200 to 650ms, while v3.3.8.1 is about 28 to 90ms. The higher the string is in size, the more exponential the time becomes. This leads to an unresponsive GUI.

Quote

I found the solution to the slow problem and was right about the 100ms timer.
Starting with v3.3.10.0, you must use Opt('TCPTimeout', 10) in your script
to behave like v3.3.8.1.

The quote is from https://www.autoitscript.com/trac/autoit/ticket/3575

So which @AutoitVersion do you use with this UDF? Im considering making a patch for this :)

 

/Tarre

Link to post
Share on other sites
  • 1 year later...

I don't manage to make it working with a Socket.IO server using NodeJs and an AutoIt Client using this library.

Do I make something wrong ?

AutoIt Client

#AutoIt3Wrapper_Change2CUI=Y
#include "..\socketIO.au3"

; Connect to server
_Io_DevDebug(True)
Global $socket = _Io_Connect(@IPAddress1, 8082, True)

If Not @error Then
    ConsoleWrite("Successfully connected to server" & @CRLF)
Else
    ConsoleWrite("Failed to open socket:" & @error & @CRLF)
    Exit
EndIf

; -------------
;   All events are registered here
; -------------

_Io_on("message", callback_serverHasGreetedUs)
_Io_on("disconnect", callback_WeDisconnectedFromServer)

; Start main loop
While _Io_Loop($socket)
    ;_Io_Emit($socket, "message", "Hello from client!")
    Sleep(500)
WEnd

; -------------
;   All event callbacks are defined here
; -------------

Func callback_serverHasGreetedUs(ByRef $socket, $message)
    MsgBox(0, "The Client", "Message received from server: " & $message & @CRLF & "Press OK to send something back to the server")
    _Io_Emit($socket, "message from client", "Hello from client!")
EndFunc   ;==>callback_serverHasGreetedUs

Func callback_WeDisconnectedFromServer($socket)
    MsgBox(0, "The Client", "Lost connection to server... Aborting!")
    Exit
EndFunc   ;==>callback_WeDisconnectedFromServer

Node.Js server

var io = require('socket.io')(8082);
// Quand un client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
    socket.emit('message', 'You are connected!');

    console.log('Someone connected !');
});

 

I connect successfully, disconnect succesfully but unable to retrieve any message from client to server or server to client.

Link to post
Share on other sites

Hi @timmalos.

Sorry to burst your bubble, but I just ported the actual concept of SocketIo, they cannot talk to each other (yet).

 

As a consolation you could try this: 

 

But instead of injecting jQuery, you could inject https://cdnjs.com/libraries/socket.io in an hidden page. I cannot guarantee that this will even work, but its worth a shot if you want your autoit-app to talk to a node.js server.

Good luck!

Link to post
Share on other sites

I have updated the UDF to 2.0.0

 

Version 2.0.0 (This update break scripts. Please consult the upgrade.md for guidance)

  • All global internal variables has been renamed.
  • Added a bunch of new API methods: _Io_RegisterMiddleware, _Io_whoAmI, _Io_IsClient, _Io_IsServer, _Io_getAllByProperty and _Io_getFirstByProperty and some more. Read more about these in the documentation.
  • _Io_socketGetProperty now has a setter method called _Io_socketSetProperty which can be used to set custom properties.
  • _Io_socketGetProperty now has a third parameter "default" which is used when a property is not found
  • Removed _Io_setEventPostScript and _Io_setEventPretScript in favor of _Io_RegisterMiddleware
  • Improved documentation (It still needs some love though)
  • Improved the verbosity of _Io_DevDebug
Link to post
Share on other sites

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2021-10-18

Link to post
Share on other sites

Hi all, almost a year later :)

 

 

Version 3.0.0 (This update break scripts. Please consult the upgrade.md for guidance)

  • Now supports serialization Scripting Dictionaries
  • Added UnitTester UDF to the mix
  • This is the last version of the current code base.

Version 3.0.0 is not gonna live long though, because I already have a 4.0 version coming up soon with major changes and improvements.

Link to post
Share on other sites

Version 4.0.0-beta (This update break scripts.)

  • Code base fully rewritten with Autoit-Events and decoupled to improve code quality and reduce bloat.
  • The new UDF is very different from 3.x.x so please checkout the UPGRADE guide to fully understand all changes
  • Added new documentation documentaion
Link to post
Share on other sites
  • 1 month later...
  • 4 weeks later...

Hi,

As I replied in your DM.

AutoIT SocketIo is built for autoit 2 autoit communication exclusivly. You would need to rebuild my whole UDF  and its deserialization dependencies to achieve the same outcome.


However "AutoiT-API-WS" is more suitable for your needs.

You could transfer data between your autoit app and Python app with a few lines of code :)

And if you want to use the "Observer design pattern",  you could API-WS in conjunction with AutoIt-Events :

 

 

 

Link to post
Share on other sites
On 11/4/2020 at 2:07 AM, x_bennY said:

very well written code @tarretarretarre

does it now supports socket.io with node.js?

Yes, or at least kindof.

My next project is going to be straight up WebSockets in AutoIt. That means you could establish connections between any language that support WebSockets, Socket Io has support for websockets, so it would be possible to make a straight port of the real Socket IO :)

But, I am working 150% with so many projects, so I dont know when I will have the time

 

Edited by tarretarretarre
CTRL + ENTER is apperently a thing
Link to post
Share on other sites
  • 1 month later...

Hi @tarretarretarre! I wish you could give me some insight on what I'm doing wrong here. I'm using your library to manage communication between two scripts via Lan and It's working flawlessly. My only issue is while testing for reconnection. After I reset my server script, I handle the event and reconnect, but my custom events are lost for the new socket.

How should I approach this scenario.

I registered my server .exe as a service so Windows re-launches it automatically, my client is able to reconnect but the events fail to be fired with "NOT_FOUND"

 

Regards!

 

JP

Link to post
Share on other sites
  • 4 weeks later...
On 1/18/2021 at 7:20 PM, pablocapi13 said:

Hi @tarretarretarre! I wish you could give me some insight on what I'm doing wrong here. I'm using your library to manage communication between two scripts via Lan and It's working flawlessly. My only issue is while testing for reconnection. After I reset my server script, I handle the event and reconnect, but my custom events are lost for the new socket.

How should I approach this scenario.

I registered my server .exe as a service so Windows re-launches it automatically, my client is able to reconnect but the events fail to be fired with "NOT_FOUND"

 

Regards!

 

JP

Hi,

 

Yes I have stumbled upon that as well. V4 is still beta and I will eventually get it patched, meanwhile, try to wrap all your _Io_On events in an function, and run that function after your reconnect attempt, that should solve your "NOT_FOUND" errors

Something like this

func RegisterEvents()
    _Io_On('SomethingHappend')
EndFunc

_Io_Connect()
 RegisterEvents()
 
 
 func ReconnectAttempt()
     _Io_Connect()
     RegisterEvents()
 EndFunc

 

Edited by tarretarretarre
Link to post
Share on other sites
  • 1 month later...

Hi tarretarretarre,

you can make a example "private message" in version 4?

here my function for select User|IP

Func _sendPM(); my function for select User|IP
    Local $iEdit = _GUICtrlListView_GetSelectionMark($UserList)
    Local $bItem = _GUICtrlListView_GetItemTextString($UserList, $iEdit)
    Local $aItem = _GUICtrlListView_GetItemTextArray($UserList, $iEdit)
    If $iEdit > -1 Then
        Local $aItem = _GUICtrlListView_GetItemTextArray($UserList, $iEdit)
        Local $user = $aItem[1]
        Local $userip = $aItem[2]
    EndIf
    ; Send message
    ;_Io_Emit($socket, "private message", $to_ip, $pm)
EndFunc

 

Link to post
Share on other sites
On 3/22/2021 at 6:45 PM, Marius462 said:

Hi tarretarretarre,

you can make a example "private message" in version 4?

here my function for select User|IP

Func _sendPM(); my function for select User|IP
    Local $iEdit = _GUICtrlListView_GetSelectionMark($UserList)
    Local $bItem = _GUICtrlListView_GetItemTextString($UserList, $iEdit)
    Local $aItem = _GUICtrlListView_GetItemTextArray($UserList, $iEdit)
    If $iEdit > -1 Then
        Local $aItem = _GUICtrlListView_GetItemTextArray($UserList, $iEdit)
        Local $user = $aItem[1]
        Local $userip = $aItem[2]
    EndIf
    ; Send message
    ;_Io_Emit($socket, "private message", $to_ip, $pm)
EndFunc

 

You could easiely

_Io_Emit($socket, "privatemessage", $to_ip & '|' & $pm)

and on the receiving func simply

Func _On_privatemessage(Const $socket, $data)

Local $arData = StringSplit($data, '|', 1)

; $arData[1] will hold the ip

; $arData[2] will hold the pm

Endfunc

 

Link to post
Share on other sites

Hi @tarretarretarre,

i heaviely modified your SoketIO.au3 3.0.0 and also wrote a small framework around it.

I removed the serilization UDF completly and added alot of safety and convenience features. Idk if you care for 3.0.0 anymore as you work on 4.0.0.

However the Client can now Guess how much load is on the Server, this work vise versa. I call it Flood Prevention. It ensures that no packets get discarded because of $g__io_nMaxPacketSize

Then i added packet validation. The packets now also get verified and discarded if corrupted. The next feature is a Safety feature where bad packets get resend. There are more little feature as for example a counter per socket for how much bytes got send and received.. etc.

All of it can be toggled and if used with the framework both side even sync their configurations.

Even tho i didnt optimise nor polished what i coded yet, i still think that it got much faster and safer.

In this picture i have 10 Clients sending constantly packets of 2048 KB
The server handling them so nice that each client can send up to 2 packets per second

Spoiler


9c5K8t2.png

 

I try to make it much faster with certain other technics or by recoding more sections. As the Issue is less with the packet size but with the packet and socket count.

Link to post
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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By tarretarretarre
      About AutoIt-Events
      AutoIt-Events is an event Observer and is a core dependency for Autoit-Socket-IO but can be used for any Autoit project.
      Example
      #include "Event.au3" ; Subscribe listeners _Event_Listen(UserCreatedEvent, SendWelcomeMail) _Event_Listen(UserCreatedEvent, RegisterNewsLetter) ; Fire event _Event(UserCreatedEvent, @UserName, "tarre.islam@gmail.com") Func UserCreatedEvent(Const ByRef $oEvent, $name, $email) ; via $oEvent you can pass data to its listeners $oEvent.add("name", $name) $oEvent.add("email", $email) $oEvent.add("id", 1) EndFunc Func SendWelcomeMail(Const $oEvent) MsgBox(64, "Welcome mail sent", "Welcome mail sent to " & $oEvent.item("name") & " with email " & $oEvent.item("email")) EndFunc Func RegisterNewsLetter(Const $oEvent) MsgBox(64, "News letter registred", "News letter bound to user id " & $oEvent.item("id")) EndFunc  
      The code is also available at Github
       
      Autoit-Events-1.0.0.zip
    • By tarretarretarre
      Version 2.x.x and 3.x.x has been moved to branch 3.x
      About Autoit-Socket-IO
      Autoit-Socket-IO is a event driven TCP/IP wrapper heavily inspired from Socket.IO with focus on user friendliness and long term sustainability.
      I constantly want to make this UDF faster and better, so if you have any suggestions or questions (beginner and advanced) Do not hesitate to ask them, I will gladly help!
      Key features
      Simple API 99% data-type serialization thanks to Autoit-Serialize Can easily be extended with your own functionality thanks to Autoit-Events "Educational" examples Data encryption thanks to _<Crypt.au3> Limitations
      Speed. This UDF will sacrifice some speed for convenience Read more in the official thread
    • By TheXman
      Purpose (from Microsoft's website)
      The HTTP Server API enables applications to communicate over HTTP without using Microsoft Internet Information Server (IIS). Applications can register to receive HTTP requests for particular URLs, receive HTTP requests, and send HTTP responses. The HTTP Server API includes SSL support so that applications can exchange data over secure HTTP connections without IIS.
      Description
      There have been several times in the past that I wanted to either retrieve information from one of my PCs or execute commands on one of my PCs, whether it was from across the world or sitting on my couch.  Since AutoIt is one of my favorite tools for automating just about anything on my PC, I looked for ways to make to make it happen.  Setting up a full blown IIS server seemed like overkill so I looked for lighter weight solutions.  I though about creating my own AutoIt UDP or TCP server but that just wasn't robust enough,  Then I found Microsoft's HTTP Server API and it looked very promising.  After doing a little research into the APIs, I found that it was flexible & robust enough to handle just about any of the tasks that I required now and in the future.  So a while back I decided to wrap the API functionality that I needed into an AutoIt UDF file to allow me to easily create the functionality I needed at the time.  It has come in very handy over the years.  Of course it wasn't all wrapped up with a nice little bow like it is now.  That only happened when I decided to share it with anyone else who could use it or learn from it.
      The example file that I included is a very granular example of the steps required to get a lightweight HTTP Server up and listening for GET requests.  The UDF is a wrapper for the Microsoft APIs.  That means to do anything over and above what I show in the example, one would probably have to have at least a general knowledge of APIs or the ability to figure out which APIs/functions to use, what structures and data is needed to be passed to them, and in what order.  However, the UDF gives a very solid foundation on which to build upon.  Of course, if anyone has questions about the UDF or how to implement any particular functionality, I would probably help to the extent that I could or point you in the right direction so that you can figure out how to implement your own solution.
      The APIs included in the UDF are the ones that I needed in the past to do what I needed to do.  If any additional APIs need to be added to the UDF file, please make those suggestions in the related forum topic.
      Being that this is basically an AutoIt wrapper for the Microsoft API functions, there's no need to create AutoIt-specific documentation.  All of the UDF functions, structures, constants, and enumerations are named after their Microsoft API counterparts.  Therefore, you can refer to Microsoft's extensive documentation of their HTTP Server API.  As stated earlier, if there is one or more APIs that you find yourself needing for your particular solution, please suggest it in the related Example Scripts forum topic.
      Related Links
      Microsoft HTTP Server API - Start Page
      Microsoft HTTP Server API - API v2 Reference
      Microsoft HTTP Server API - Programming Model
    • By YogendraAtluri
      Hi, 
      I am new to AutoIT scripting and I am still learning. I am trying to communicate with a Labview application that acts like a server. it basically takes commands from the client. But for some commands, it also send back some data. 
      When i am sending commands from my script, i can see that the labview is getting them. But i am not able to get anything back. I tried different code pieces that are available online in the forum.
      This is the working piece of code which i been using to send data.
      #cs This module is used to establish tcp connection with lab view #ce #include <File.au3> Func SendCmd($cmd) TCPStartup() Local $IpAddress="192.168.10.101" Local $Port="5353" $Labview = TCPConnect($IpAddress,$Port) If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ).' & @CRLF) TCPCloseSocket($Labview) TCPShutdown() Exit EndIf TCPSend($Labview, $cmd & @CRLF) TCPCloseSocket($Labview) TCPShutdown() EndFunc SendCmd("wt42d")  
      This is slightly modified code to send and receive data, which is not working. I am not getting any response back
      SendCmd("galil") Func SendCmd($cmd) TCPStartup() Local $IpAddress="192.168.10.101" Local $Port="5353" $Labview = TCPConnect($IpAddress,$Port) If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ).' & @CRLF) TCPCloseSocket($Labview) TCPShutdown() Exit EndIf TCPSend($Labview, $cmd & @CRLF) $ip = @IPAddress1 ;create listening socket $Listensocket = TCPListen($ip, $Port) ConsoleWrite("Listening to Socket - " & $Listensocket & @CRLF) If $Listensocket = -1 Then ConsoleWrite("Exiting..." & @CRLF) Exit EndIf ;Accept incoming clients and recieve info While 1 $connectedsocket = TCPAccept($Listensocket) ConsoleWrite("Connecting to Socket - " & $connectedsocket & "Error -" & @error & @CRLF) If $ConnectedSocket >= 0 Then $ip2 = TCPRecv($connectedsocket,1000000) EndIf WEnd TCPCloseSocket($connectedsocket) TCPCloseSocket($Labview) TCPShutdown() EndFunc I am not getting anything back. I am getting the following output in the console
      +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Listening to Socket - 544 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 its going through that loop forever. i need to force stop it.
      But when i open putty and send the same command, i am getting response right away. 
      Can someone please help me with that.
      Thanks in advance
      Regards
      Yogendra
    • By argumentum
      I can TCP/IP in AutoIt, hence, make a HTTP deamon. Now, how can I HTTPS to use SSL !??
      Well, Apache has this "mod_proxy.so" module that can let me have SSL and what not is in Apache.
      All that is needed is to tell Apache what I wanna do by editing httpd.conf .
      # Implements a proxy/gateway for Apache. # 1. Open /Applications/XAMPP/etc/httpd.conf # 2. Enable the following Modules by removing the # at the front of the line. # - LoadModule rewrite_module modules/mod_rewrite.so # - LoadModule proxy_module modules/mod_proxy.so # - LoadModule proxy_http_module modules/mod_proxy_http.so # # 3. Copy and Paste below to the bottom of httpd.conf # <IfModule mod_proxy.c> ProxyRequests On <Proxy *> Order deny,allow Allow from all </Proxy> ProxyVia Off ProxyPreserveHost Off ProxyPass /home/ http://127.0.0.1:84/home/ ProxyPassReverse /home/ http://127.0.0.1:84/home/ SetEnv proxy-nokeepalive 1 # ..since we are not using "keep-alive", we are using "close" </IfModule> ...et voila  
      I'm using XAMPP ( https://www.apachefriends.org/download.html )
      and this is my solution to avoid coding in PHP, as I feel more comfortable coding in AutoIt.
      A "muli-thread or concurrency" can be done by forking the socket ( https://www.autoitscript.com/forum/topic/199177-fork-udf-ish/ )
      but responses are under 20 ms., so I feel fine with a single thread.
      I modified an example ( attached below ), so can try out the concept.
      PS: I am not an Apache guru. I just discovered this and it opens a world of possibilities. In my case, I'm thinking of an API to query SQLite 
      PS2: I'm not gonna make Poll but do click like if you do  
       
      201673-json-http-post-serverlistener.au3
×
×
  • Create New...