Jump to content
tarretarretarre

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

Recommended Posts

Autoit-Socket-IO

Introduction

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 created this UDF because I was fascinated how Socket.IO made a such scary task "reliable and secure networking" so simple for the developer. So this was my main motivation.

I constantly want to make this UDF faster and better, so if you have any suggestions. Do not hesitate to make requests!

Features

  • Flexiable and easy to understand API
  • Above avarage documentation
  • "Fully featured" examples
  • Security in form of data encryption and middleware-support

Limitations

  • Speed. Because I want this UDF to be as flexible and simple as possible. Sometimes speed is sacrificed, but that does not mean i don't try to .
  • It is not possible to emit objects mainly because autoit does not support serialization.
  • Only 1D-arrays can be emitted (2D arrays will probably never be supported)

Success story

Since December 2017-now I have used version 1.5.0 in an production environment for 40+ clients with great success, the only downtime is planned windows updates and power outages.

Getting started

  • Download the script from AutoIt or pull it from the official github repo git@github.com:tarreislam/Autoit-Socket-IO.git and checkout the tag 2.0.0
  • The documentation is located at Docs\index.html
  • Take a look in the examples/ folder

Changelog

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

 

Newest version (2019-09-29!)
Autoit-Socket-IO-2.0.0.zip

Older versions (Not supported anymore)

Autoit-Socket-IO-1.0.0.zip Autoit-Socket-IO-1.1.0.zip Autoit-Socket-IO-1.3.0.zip Autoit-Socket-IO-1.4.0.zip Autoit-Socket-IO-1.5.0.zip

Edited by tarretarretarre
Update

Share this post


Link to post
Share on other sites

It looks interesting.
I have to testify.


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  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 *

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 * 

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 TaskScheduler

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 *

"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: 2019-10-01

Share this post


Link to post
Share on other sites

Hello!

I have updated the UDF with a new features and improvements

  • Version 1.0.0 (This update DOES NOT break scripts)
  • Added data encryption (Using Autoit's UDF Crypt.au3) See more at _Io_EnableEncryption
  • Added new method _Io_Disconnect which can be used with both servers and clients
  • Improved package-handling to increase performance
  • Increased the limit of Broadcasted/Emit parameters from 10 to 16

Share this post


Link to post
Share on other sites

Hi again!

This will probably be the last update in a while, since i think i covered the most interesting parts from Socket.io.

Version 1.1.0 (This update DOES NOT break scripts)

  • Fixed bug when Emitting / Broadcasting without any parameters causing a $fCallback crash
  • Optimized Package-handling once again.
  • Added 1D-Array support (Endless nestning).
  • Added Subscriptions (See _Io_Subscribe _Io_Unsubscribe and _Io_BroadcastToRoom).
  • Added new example for subscriptions (Be sure to use different room names when joining with clients)
  • Added Unit testing (See Tests\Runner.au3 and Tests\Tests.au3, to run tests you need a udf found here: https://github.com/tarreislam/Autoit-Unit-Tester)

Share this post


Link to post
Share on other sites

So I thought!

Here is a fast-forward update

Version 1.3.0 (This update DOES NOT break scripts)

  • Got rid of unnecessary Redims with sockets and subscriptions in the main loop (This increased write performence greatly)
  • Changed $iMaxDeadSocketsBeforeTidy from 100 to 1000
  • Changed _Io_setRecvPackageSize($nPackageSize = 2048) to _Io_setRecvPackageSize($nPackageSize = 4096) because 2017.
  • Added Tests for both subscriptions and the automatic TidyUp
  • Added a new server method: _Io_getMaxConnections
  • Added a new server method: _Io_getMaxDeadSocketsCount
  • Added a fifth parameter to the _Io_Listen method called $iMaxConnections which defaults to 100000. If the iMaxConnection + 1 user connects, they will be instantly disconnected.
  • Added a parameter to _Io_Disconnect called $socket which defaults to null. If the iMaxConnections + 1 client connects, they will be instantly disconnected.

Version 1.2.0 (This update DOES NOT break scripts)

  • Added an option to set the packet-size of TCP-transports, see _Io_setRecvPackageSize
  • Got rid of unnecessary StringLen's in _Io_loop
  • Changed __Io_TidyUp to _Io_TidyUp and added it to the public Api reference list.
  • Changed $iMaxDeadSocketsBeforeTidy default value from 1000 to 100 and added an option to disable it, read more at _Io_Listen
  • Changed $bAutoReconnect from False to True.
  • Fixed gitignore epicZ fail
  • Improvemend Documentation

Share this post


Link to post
Share on other sites

Hello,

First thank you for your work, but I try to find out how to comunicate between client. I want to send a popup to another client.

Any idea ? It seem the Broadcast method send to everyone.

Share this post


Link to post
Share on other sites

Ok I made it :

Serveur

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

;Start server
Global $socket = _Io_Listen(8080)

If Not @error Then
    ConsoleWrite("Listening on port 8080" & @CRLF)
Else
    ConsoleWrite("Failed to open socket:" & @error & @CRLF)
    Exit
EndIf

; -------------
;   All events are registered here
; -------------
_Io_on("join", ClientJoined)
_Io_on("message", Message)

; Start main loop
While _Io_Loop($socket)
WEnd

Func Message(ByRef $socket, $name, $ip , $message)
    ; Transit message the message
    ;_Io_BroadcastToAll($socket, "message", $name, $message)
    _Io_BroadcastToAll($socket, $ip, $name & ": " & $message)
    ConsoleWrite($name & ": " & $message & @CRLF)
EndFunc

Func ClientJoined(ByRef $socket, $name)
    ConsoleWrite("Client joined: " & $name & @CRLF)
EndFunc

client 1 who send message to client 2 with the right ip

#AutoIt3Wrapper_Change2CUI=Y
#include ".\UDF\socketIO.au3"
#include ".\UDF\Toast.au3"
#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

; Its recommended to always use Gui events to remove the programs main focus from updating the GUI
Opt("GUIOnEventMode", 1)

Global $username = @UserName

#Region ### START Koda GUI section ### Form=
Global $Form1 = GUICreate("Form1", 272, 154, 636, 373)
Global $Input1 = GUICtrlCreateInput("IP", 32, 16, 217, 21)
Global $Input2 = GUICtrlCreateInput("Message", 32, 48, 217, 21)
Global $Button1 = GUICtrlCreateButton("Button1", 88, 88, 97, 33)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

; Connect to server
Global $socket = _Io_Connect(@IPAddress1, 8080, True)
If @error Then
    ConsoleWrite("Failed to open socket:" & @error & @CRLF)
    Exit
EndIf

; Register gui events
GUICtrlSetOnEvent($Button1, "SendMessage")
GUISetOnEvent($GUI_EVENT_CLOSE, "_quit")

; Notify server that we are here!
_Io_Emit($socket, "join", $username)

; Start main loop
While _Io_Loop($socket)
WEnd

; Gui functions
Func SendMessage()
    ; Send message
    _Io_Emit($socket, "message", $username , GUICtrlRead($Input1) , GUICtrlRead($Input2))
    ; Clear input
    GUICtrlSetData($Input2, "")
EndFunc

Func _quit()
    Exit
EndFunc

client 2

#include ".\UDF\socketIO.au3"
#include ".\UDF\Toast.au3"

Global $aRet[2]

; Connect to server
Global $socket = _Io_Connect("192.168.1.254", 8080, True)
If @error Then
    ConsoleWrite("Failed to open socket:" & @error & @CRLF)
    Exit
EndIf

; -------------
;   All events are registered here
; -------------
_Io_on("192.168.1.1", callback);ip client

; Start main loop
While _Io_Loop($socket)
WEnd

Func callback(ByRef $socket, $message)
    ;MsgBox(0, "The Client", $message)
    $aRet = _Toast_Show(0, "Form client 1", $message, 5)
    _Toast_Hide()
EndFunc   ;==>callback_serverHasGreetedUs

 

Share this post


Link to post
Share on other sites

Hi and thank you!

I see what you are trying to do, instead of binding an event for each client, you could do something like this instead:

 

Note: I use UDF global variables (which is bad practise), theres no guarantee that this will be working in the future and I will address this issue for the next update.

 

In the server, add this:

_Io_On("private message", Callback_PrivateMessage)


Func Callback_PrivateMessage(ByRef $socket, $message, $to_ip)

    ; Get the person whos trying to send an private message
    Local $sender_ip = _Io_socketGetProperty($socket, "ip")

    ; Loop through each socket stored on server
    For $i = 1 To $__g_io_extended_sockets[0]
        ; Open the ExtendedSocket array
        Local $aExtendedSocket = $__g_io_extended_sockets[$i]
        ; Grab the socket
        Local $client_socket = $aExtendedSocket[0]
        ; Grab the ip
        Local $client_ip = $aExtendedSocket[1]

        ; Compare the ip that the client sent us (Also ignore dead sockets
        If $to_ip == $nClientIp AND $__g_io_sockets[$i] <> Null  Then
            ; Send
            _Io_Emit($client_socket, "private message", $sender_ip, $message)

            ; Remove this exitloop if you want continue search after the first result
            ExitLoop
        EndIf

    Next
EndFunc

 

On the client, add this:

_Io_On("private message", Callback_PrivateMessage)

Func Callback_PrivateMessage(ByRef $socket, $sender_ip, $message)

    MsgBox(0, "Private message from " & $sender_ip, $message)

EndFunc

 

Too send private messages from the client do like so:

_Io_Emit($socket, "private message", "Secret message", "192.168.0.10")

 

 

I have not tested this code because im not home

Share this post


Link to post
Share on other sites

Thanks I get it work :

Server :

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

;Start server
Global $socket = _Io_Listen(8080)

If Not @error Then
    ConsoleWrite("Listening on port 8080" & @CRLF)
Else
    ConsoleWrite("Failed to open socket:" & @error & @CRLF)
    Exit
EndIf

_Io_on("join", ClientJoined) ;réaction a l'evenement "join"
_Io_On("private message", Callback_PrivateMessage)

; Start main loop
While _Io_Loop($socket)
WEnd

Func ClientJoined(ByRef $socket, $name)
    ConsoleWrite("Client joined: " & $name & @CRLF)
EndFunc

Func Callback_PrivateMessage(ByRef $socket,  $to_ip , $message)
    ConsoleWrite("Private Message " & $message & " vers " & $to_ip & @CRLF)
    ; Get the person whos trying to send an private message
    Local $sender_ip = _Io_socketGetProperty($socket, "ip")

    ; Loop through each socket stored on server
    For $i = 1 To $__g_io_extended_sockets[0]
        ; Open the ExtendedSocket array
        Local $aExtendedSocket = $__g_io_extended_sockets[$i]
        ; Grab the socket
        Local $client_socket = $aExtendedSocket[0]
        ; Grab the ip
        Local $client_ip = $aExtendedSocket[1]

        ; Compare the ip that the client sent us (Also ignore dead sockets
        If $to_ip = $client_ip AND $__g_io_sockets[$i] <> Null  Then
            ; Send
            _Io_Emit($client_socket, "private message", $sender_ip, $message)

            ; Remove this exitloop if you want continue search after the first result
            ExitLoop
        EndIf
    Next
EndFunc

client who send private message

#include ".\UDF\socketIO.au3"
#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

; Its recommended to always use Gui events to remove the programs main focus from updating the GUI
Opt("GUIOnEventMode", 1)

Global $username = @UserName

#Region ### START Koda GUI section ### Form=
Global $Form1 = GUICreate("Form1", 272, 154, 636, 373)
Global $Input1 = GUICtrlCreateInput("IP", 32, 16, 217, 21)
Global $Input2 = GUICtrlCreateInput("Message", 32, 48, 217, 21)
Global $Button1 = GUICtrlCreateButton("Button1", 88, 88, 97, 33)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

; Connect to server
Global $socket = _Io_Connect("192.168.1.10", 8080, True)
If @error Then
    MsgBox(0,"Failed to open socket:",@error & @CRLF,5)
    Exit
EndIf

; Register gui events
GUICtrlSetOnEvent($Button1, "SendMessage")
GUISetOnEvent($GUI_EVENT_CLOSE, "_quit")

; Notify server that we are here!
_Io_Emit($socket, "join", $username);envoi au serveur l'evenement "join" qui indique que l'utilisateur est connecté

; Start main loop
While _Io_Loop($socket)
WEnd

; Gui functions
Func SendMessage()
    ; Send message
    _Io_Emit($socket, "private message", GUICtrlRead($Input1) , GUICtrlRead($Input2))
    ; Clear input
    GUICtrlSetData($Input2, "")
EndFunc

Func _quit()
    Exit
EndFunc

client who receive

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=n
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include ".\UDF\socketIO.au3"

Global $aRet[2]

; Connect to server
Global $socket = _Io_Connect("192.168.1.10", 8080, True)
If @error Then
    MsgBox(0,"Failed to open socket:",@error & @CRLF,5)
    Exit
EndIf

_Io_On("private message", Callback_PrivateMessage)
; Notify server that we are here!
_Io_Emit($socket, "join", @UserName & @CRLF)

; Start main loop
While _Io_Loop($socket)
WEnd

Func Callback_PrivateMessage(ByRef $socket, $sender_ip, $message)
    MsgBox(0, "Private message from " & $sender_ip, $message)
EndFunc

 

Share this post


Link to post
Share on other sites

You can find some examples at GitHub: https://github.com/tarreislam/Autoit-Socket-IO

ccqL8C7.png

P.S

51 minutes ago, Trong said:

UPD 

I think you mean UDP :)


A cross-platform implementation of the AutoIt language

My contributions to the AutoIt Community ##AutoIt at freenode, real-time chat

3fHNZJ.gif

Spoiler

If I have hurt or offended you in anyway, Please accept my apologies, I never (regardless of the situation) intend to do that to anybody.

Share this post


Link to post
Share on other sites

Hi!

I will not officially support UDP, but technically you could replace all TCP commands with UDP.

Regarding filetransfers: 

Open the file with https://www.autoitscript.com/autoit3/docs/functions/FileOpen.htm  $FO_BINARY mode

Split and transmit each chunk of the file until you reach the end.

 

I will probably add an example for the next update.

Share this post


Link to post
Share on other sites

Yo, here is a medium-big update containing new features, examples and optimizations.

 

I Decided to NOT include any Filetransfer examples, I rather create a separate thread about it.

 

Version 1.4.0 (This update DOES NOT break scripts)

  • Added a new server method: _Io_getSockets which will return an array of all sockets. See more in the doc
  • Added a banning-system, see more at: _Io_getBanlist, _Io_Ban, _Io_Sanction, _Io_IsBanned
  • Added a new default event for clients banned. See more at default events
  • Added two new client and server methods _Io_setEventPreScript And _Io_setEventPostScript. The intent for these is to not DRY when doing debug \ tasks that requires to be ran before or after events.
  • Added a new client and server method _Io_ClearEvents.
  • Added a third optional parameter to _Io_On called $socket, you may only pass the socket returned from _Io_Listen or _Io_Connect. The intent for this change is to allow for server + client in the same envoirment.
  • Added a second parameter to _Io_Loop called $WhoAmI which should used with the new enums $_IO_SERVER and $_IO_CLIENT. The intent for this change is to allow for server + client in the same envoirment.
  • Added a new client method _Io_TransferSocket.
  • Added a new server method _Io_getActiveSocketCount.
  • Optimations, avoiding Redims and unnecessary nested arrays as good as possible etc.

Share this post


Link to post
Share on other sites

For group chats, look at Subscriptions. Example here: https://github.com/tarreislam/Autoit-Socket-IO/tree/master/Example - Chat with subscriptions

Client to client still have to go through the server, look at post #9. I will add an example for a future release :)

Share this post


Link to post
Share on other sites

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 Docs\. The docs are generated so its a 1 to 1 reflection of the UDF headers. Print of documentation
  • Added a production ready server example.
  • Added a new method: _Io_DevDebug which will display useful information when debugging.
  • Added a new method: _Io_SetMaxRecvPackageSize which defaults to whatever _Io_setRecvPackageSize is set to.
  • Added a new method: _Io_setOnPrefix which defaults to _On_
  • Added a new default client & server event called flood. Flood occurs when exceeding the $__g_io_nMaxPacketSize. $__g_io_nMaxPacketSize is set by _Io_SetMaxRecvPackageSize
  • Fixed the 16 parameter limit when sending data with _Io_Emit, _Io_Broadcast, _Io_BroadcastToAll and _Io_BroadcastToRoom. This works on the same premise that AutoIt's Call Does
  • Fixed a TRUNCATION problem when receiving packages which could cause crashes!
  • Fixed a programming error which caused $__g_ionPacketSize to reset to default 4096 if _Io_Connect or _Io_listenwere called after _Io_setRecvPackageSize
  • Fixed _Io_setEventPreScript and _Io_setEventPostScript They didnt work. Lol.
  • Changed how events are fired so the client cannot crash the server by sending the wrong number of parameters (This also allows for optional parameters on callbacks)
  • Changed _Io_On. The second parameter $fCallback can now be set to null. Doing this, the function assumes that the callback is: _On_<eventName>.
Edited by tarretarretarre

Share this post


Link to post
Share on other sites

I wait for the feature: transfer files quickly as fast as the current network card.

Like downloading a file from within a LAN, or outside the INTERNET.


Regards,
 

Share this post


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 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
    • By Chimp
      This is a little experiment that makes use of a "Browser Control" embedded in a GUI in order to be able to use AutoIt, HTML, JavaScript and CSS all together.
      This little toy will only work on systems with IE11.
      The purpose is to drag all the names of the scientists & drop on the right ones. (among scientists it has also infiltrated an intruder). I hope you find it entertaining.
      I've posted it here in the hope to have some suggestions on how to improve it all (I mean the interaction between Autoit Javascript html and css). Thanks
      ; this works on systems with IE11 ; ------------------------------- #include <GUIConstantsEx.au3> #include <array.au3> Global $oIE, $oDocument, $ohJS, $sDroping Global $iCorrect = 0, $iGoal = 11 Example() Exit Func Example() Local $aScientists[12][2] = _ [["Schrodinger", "Schrodinger"],["Planck", "Planck"],["Pauli", "Pauli"],["Einstein", "Einstein"], _ ["Chimp", "Chimp"],["Dirac", "Dirac"],["Heisenberg", "Heisenberg"],["Born", "Born"], _ ["De Broglie", "De_Broglie"],["Bohr", "Bohr"],["Sommerfeld", "Sommerfeld"],["", "empty"]] Local $oIE = ObjCreate("Shell.Explorer.2") ; Create a BrowserControl Local $hGUI = GUICreate("", 660, 600, 30, 30) GUICtrlCreateObj($oIE, 0, 0, 660, 600) ; Place BrowserControl on the GUI GUISetState() ;Show GUI $oIE.navigate('about:blank') ; file:///' & @ScriptDir & '\WhoIsWho.html') While Not String($oIE.readyState) = 'complete' ; wait for about:blank Sleep(100) WEnd ; this waits till the document is ready to be used (portion of code from IE.au3) While Not (String($oIE.readyState) = "complete" Or $oIE.readyState = 4) Sleep(100) WEnd While Not (String($oIE.document.readyState) = "complete" Or $oIE.document.readyState = 4) Sleep(100) WEnd $oIE.document.Write(_GetHTML()) ; inject lising directly to the HTML document: $oIE.document.close() ; close the write stream $oIE.document.execCommand("Refresh") While Not String($oIE.readyState) = 'complete' ; wait for readyState after a refresh Sleep(100) WEnd ; https://msdn.microsoft.com/en-us/library/52f50e9t(v=vs.94).aspx ; $ohJS is a reference to the javascript Global Obj ; ------------------------------------------------- $ohJS = $oIE.document.parentwindow.JSglobal $oDocument = $oIE.document Local $oTable1 = $ohJS.table1 Local $oTable2 = $ohJS.table2 _Randomize($aScientists, $oTable1) ; --- Setup events ------------ ; https://msdn.microsoft.com/en-us/library/hh801967(v=vs.85).aspx Local $aoEventObject[2] $aoEventObject[0] = ObjEvent($oTable1, "IEEvent_", "HTMLTableEvents2") $aoEventObject[1] = ObjEvent($oTable2, "IEEvent_", "HTMLTableEvents2") ; ----------------------------- ; Loop until the user exits. While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch If $iCorrect = $iGoal Then _Goal() _Randomize($aScientists, $oTable1) $iCorrect = 0 EndIf WEnd ; the end For $i = 0 To UBound($aoEventObject) - 1 $aoEventObject[$i] .stop Next $aoEventObject = 0 ; Kill the Event Object $oIE = 0 ; Remove IE from memory (not really necessary). GUIDelete($hGUI) ; Remove GUI EndFunc ;==>Example ; --- event management zone --- ; following functions are fired by events occurred in the browser control Volatile Func IEEvent_onDragstart($oEvent) ; we save the ID of the dragged obj into the $sDroping variable ; for a later use in the drop function $sDroping = $oEvent.srcElement.ID EndFunc ;==>IEEvent_onDragstart Volatile Func IEEvent_onDragOver($oEvent) $ohJS.event.preventDefault() EndFunc ;==>IEEvent_onDragOver Volatile Func IEEvent_onDrop($oEvent) $ohJS.event.preventDefault() If $sDroping <> "" Then If $oDocument.getElementById($sDroping).innerText <> $oEvent.srcElement.innerText Then If $oEvent.srcElement.ClassName = $oDocument.getElementById($sDroping).ClassName Then $oEvent.srcElement.innerText = $oDocument.getElementById($sDroping).innerText $oDocument.getElementById($sDroping).innerText = "" $oDocument.getElementById($sDroping).draggable = False $oDocument.getElementById($sDroping).setAttribute("style") = "background-color: #80ff80;" $iCorrect += 1 Else For $i = 1 To 3 $oDocument.getElementById($sDroping).setAttribute("style") = "background-color: #ff0000;" Sleep(125) $oDocument.getElementById($sDroping).setAttribute("style") = "background-color: #ffffff;" Sleep(125) Next EndIf EndIf $sDroping = "" EndIf EndFunc ;==>IEEvent_onDrop Func _Randomize(ByRef $aScientists, ByRef $oTable) Local $iRows = ($oTable.rows.length) - 1 Local $iCols = ($oTable.rows.item(0).cells.length) - 1 Local $index _ArrayShuffle($aScientists) For $y = 0 To $iRows For $x = 0 To $iCols $index = ($y * ($iCols + 1)) + $x $oTable.rows.item($y).cells.item($x).innerText = $aScientists[$index][0] ; text $oTable.rows.item($y).cells.item($x).className = $aScientists[$index][1] ; class $oTable.rows.item($y).cells.item($x).draggable = $aScientists[$index][0] <> "" Next Next EndFunc ;==>_Randomize Func _Goal() Local $oTable1 = $ohJS.table1 ; names Local $oTable2 = $ohJS.table2 ; photos Local $iRows = ($oTable1.rows.length) Sleep(250) Local $iCols = 6 ; ($oTable1.rows.item(0).cells.length) Local $aIndex[$iRows * $iCols], $sTemp For $i = 0 To UBound($aIndex) - 1 $aIndex[$i] = $i ; + 1 Next _ArrayShuffle($aIndex) For $i = 0 To UBound($aIndex) - 1 $oTable2.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).innerText = "" $oTemp0 = $oTable2.rows $oTemp1 = $oTemp0.item(Int($aIndex[$i] / $iCols)).cells $oTemp2 = $oTemp1.item(Mod($aIndex[$i], $iCols)).getAttribute("style") $oTable2.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = "background-color: " & _rndColor() Sleep(100); MsgBox(0,"Debug",$sTemp) $oTable2.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = $oTemp2 Next For $x = 1 To 2 For $i = 0 To UBound($aIndex) - 1 $oTable1.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = "background-color: " & _rndColor() Sleep(100) $oTable1.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = "background-color: #ffffff;" Next Next EndFunc ;==>_Goal Func _rndColor() Return String("#" & Hex(Random(0, 255, 1), 2) & Hex(Random(0, 255, 1), 2) & Hex(Random(0, 255, 1), 2) & ";") EndFunc ;==>_rndColor Func _GetHTML() Local $sHTML = _ "<!DOCTYPE HTML>" & @CRLF & _ "<html>" & @CRLF & _ "<head>" & @CRLF & _ "<meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" />" & @CRLF & _ " <script type=""text/javascript"">" & @CRLF & _ " var JSglobal = (1,eval)(""this"");" & @CRLF & _ " </script>" & @CRLF & _ "</head>" & @CRLF & _ "<body>" & @CRLF & _ "<h2>Who is who?</h2>" & @CRLF & _ "<p>Drag&Drop names on the right scientist</p>" & @CRLF & _ "<img src=""https://i.imgur.com/STWql7w.jpg""" & @CRLF & _ "height=""394"" width=""640""" & @CRLF & _ "style=""position: absolute; left: 10px; top: 100px;"">" & @CRLF & _ "" & @CRLF & _ "<style>" & @CRLF & _ ".target td {width: 100px; height: 160px; text-align: center; color: white; font-weight: bold; vertical-align: bottom; border: 0px solid grey;}" & @CRLF & _ ".source td {width: 100px; height: 30px; text-align: center; border: 1px solid red;}" & @CRLF & _ "</style>" & @CRLF & _ "" & @CRLF & _ "<table class=""target"" style=""position: absolute; left: 25px; top: 100px;"" id=""table2"">" & @CRLF & _ " <tr><td class=""Schrodinger""></td><td class=""Planck""></td><td class=""Pauli""></td><td class=""Einstein""></td><td class=""Chimp""></td><td class=""Dirac""></td></tr>" & @CRLF & _ " <tr><td class=""Heisenberg""></td><td class=""Born""></td><td class=""De_Broglie""></td><td class=""Bohr""></td><td class=""Sommerfeld""></td><td class=""empty""></td></tr>" & @CRLF & _ "</table>" & @CRLF & _ "" & @CRLF & _ "<table class=""source"" style=""position: absolute; left: 10px; top: 504px;"" id=""table1"">" & @CRLF & _ " <tr><td ID=""td1""></td><td ID=""td2""></td><td ID=""td3""></td><td ID=""td4"" ></td><td ID=""td5"" ></td><td ID=""td6"" ></td></tr>" & @CRLF & _ " <tr><td ID=""td7""></td><td ID=""td8""></td><td ID=""td9""></td><td ID=""td10""></td><td ID=""td11""></td><td ID=""td12""></td></tr>" & @CRLF & _ "</table>" & @CRLF & _ "</body>" & @CRLF & _ "</html>" Return $sHTML EndFunc ;==>_GetHTML  
    • By AoRaToS
      I started working on this program in the summer of 2008 then I stopped cause I faced some problems I couldn't overcome back then. Now that I've practiced more and have become a better scripter/programmer I'm releasing the program to the public to get some opinions. I know it's not a new concept but it's the first program I started besides some small stuff I did just for practice! I won't post the source code yet because it's still under construction, although I'm sure I've posted early stages of the code with bugs in the past in some topic...
      What I wanted was a simple, small, serverless program that would work without installation cause I wanted it for where I work, so I ended up with this!
      I have attached some images of various versions, also visit the forum thread.
      The package includes s!mpL3 LAN Messenger and the full change log.
      Current version 2.9.9.1! [04/07/2019]
      Check the Change Log below!
       
       
      http://www.autoitscript.com/forum/index.php?showtopic=88782
       
       
       
      Read the license before using this software.
       
×
×
  • Create New...