Jump to content
Jefrey

TCPServer UDF (multi client, event-based, able to bind console app to socket)

Recommended Posts

Hi guys/girls!

I'm gonna share this UDF I made today.

It allows you to easily create TCP servers and set actions depending on three events: OnConnect, OnDisconnect and OnReceive.

It is also multi client (you can set the clients limit) and you can also bind a Console-based executable to the socket (similar to -e parameter in NetCat). This feature is useful if you want to use some Console UDF to create your TCP server and don't want to mix it with the TCP functions. Also, as it runs on background just firing events, it won't pause your script while listening/receiving, so you can do anything else (stop and restart the server, allow the user to click buttons or just wait on an infinite loop) that your callbacks will be called once the event is fired.

It's also very easy to use. See this examples:

Example #1: A basic server

By running this (then connecting to the server using Netcat), you will receive a message box telling you when some user connects or disconnects (the socket ID and his IP address is passed as parameter to your callback function) and also when the user sends something over the TCP socket (the data sent is passed as parameter).

#cs
    Download netcat at https://eternallybored.org/misc/netcat/
    Execute this script
    Run in CMD:
    nc -vv 127.0.0.1 8081
#ce

#include "TCPServer.au3"

; First we set the callback functions for the three events (none of them is mandatory)
_TCPServer_OnConnect("connected")
_TCPServer_OnDisconnect("disconnect")
_TCPServer_OnReceive("received")

; And some parameters
_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

; Finally we start the server at port 8081 at any interface
_TCPServer_Start(8081)

Func connected($iSocket, $sIP)
    MsgBox(0, "Client connected", "Client " & $sIP & " connected!")
    _TCPServer_Broadcast('new client connected guys', $iSocket)
    _TCPServer_Send($iSocket, "Hey! Write something ;)" & @CRLF)
    _TCPServer_SetParam($iSocket, "will write")
EndFunc   ;==>connected

Func disconnect($iSocket, $sIP)
    MsgBox(0, "Client disconnected", "Client " & $sIP & " disconnected from socket " & $iSocket)
EndFunc   ;==>disconnect

Func received($iSocket, $sIP, $sData, $sPar)
    MsgBox(0, "Data received from " & $sIP, $sData & @CRLF & "Parameter: " & $sPar)
    _TCPServer_Send($iSocket, "You wrote: " & $sData)
    _TCPServer_SetParam($iSocket, 'will write again')
EndFunc   ;==>received

While 1
    Sleep(100)
WEnd

Example #2: A basic HTTP server (just one page, as it is just an example)

In this example, we run this code and point our browser to the address mentioned on the comments. A basic "It works!" page is show.

#cs
    Run this script
    Point your browser to http://localhost:8081/
#ce

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)


Func received($iSocket, $sIP, $sData, $sParam)

    _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
                    "Content-Type: text/html" & @CRLF & @CRLF & _
                    "<h1>It works!</h1>" & @CRLF & _
                    "<p>This is the default web page for this server.</p>" & @CRLF & _
                    "<p>However this server is just a 26-lines example.</p>")
    _TCPServer_Close($iSocket)

EndFunc   ;==>received

While 1
    Sleep(100)
WEnd

Example #3: A telnet-like server (Command Prompt bound to the socket after password requesting)

By running this example and connecting with Netcat, we will be asked for a password, which is 12345 as we set on the script. If the password is correct, we will see the Command Prompt live-updated (try running a ping to some server, for example).

#cs
    Download netcat at https://eternallybored.org/misc/netcat/
    Execute this script
    Run in CMD:
    nc -vv 127.0.0.1 8081
#ce

#include "TCPServer.au3"

Global $sPassword = "12345" ; input server password here

_TCPServer_OnConnect("connected")
_TCPServer_OnDisconnect("disconnect")
_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)

Func connected($iSocket, $sIP)
    _TCPServer_Send($iSocket, "Welcome! Please input password: ")
    _TCPServer_SetParam($iSocket, 'login')
EndFunc   ;==>connected

Func disconnect($iSocket, $sIP)
    MsgBox(0, "Client disconnected", "Client " & $sIP & " disconnected from socket " & $iSocket)
EndFunc   ;==>disconnect

Func received($iSocket, $sIP, $sData, $sParam)
    If $sParam = "login" Then
        If $sData <> $sPassword Then
            _TCPServer_Send($iSocket, "Wrong password. Try again: ")
            Return
        Else
            _TCPServer_SetParam($iSocket, 'command')
            _TCPServer_BindAppToSocket($iSocket, 'cmd.exe')
        EndIf
    ElseIf $sParam = "command" Then
        _TCPServer_SendToBound($iSocket, $sData)
    EndIf

EndFunc   ;==>received

While 1
    Sleep(100)
WEnd

The limit is your imagination? Well, no sure. We have this limit:

  • You can't create more than one server with this UDF in the same script. However, you can pause and resume (read 'stop and start again') your server at any time in your script, without having to reset the server settings. And of course you can have many clients (or just one, it's your choice!) in the same server. Or run multiple instances.

Functions list:

_TCPServer_Start

_TCPServer_Stop

_TCPServer_Close

_TCPServer_Send

_TCPServer_Broadcast

_TCPServer_SetParam

_TCPServer_BindAppToSocket

_TCPServer_SendToBound

_TCPServer_UnBindAppToSocket

_TCPServer_GetMaxClients

_TCPServer_IsServerActive

_TCPServer_ListClients

_TCPServer_OnConnect

_TCPServer_OnDisconnect

_TCPServer_OnReceive

_TCPServer_SetMaxClients

_TCPServer_DebugMode

_TCPServer_AutoTrim

_TCPServer_SocketToIP

_TCPServer_SocketToConnID

_TCPServer_ConnIDToSocket

 

Help file and more examples included!

Latest version: 1.0.0.1

Download: TCPServer UDF.rar

Changelog

  • 1.0 - First release - 18/04/2015
  • 1.0.0.1 - Bug fix __TCPServer_Accept internal function / help file recompiled - 26/04/2015

Perhaps you will need to uncompress the file first, so the help file will work.

Fork this on Github: http://github.com/jesobreira/TCPServerUDF

TCPServer UDF.rar

 

Edited by Jefrey

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites

Help FIle not working for me (Win8.1 X64)

it opens, and i get a tree with all functions, but no text and the name is still TCPMaker, which might have been a working title

post-5062-0-99696300-1429379591_thumb.jp

Edited by Allow2010

Share this post


Link to post
Share on other sites

Help FIle not working for me (Win8.1 X64)

it opens, and i get a tree with all functions, but no text and the name is still TCPMaker, which might have been a working title

 

Hi, thanks for your reply!

That looks strange... But I've uploaded a HTML version on the original post. Could you test it, please?


My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites

html version works in firefox but some pictures are missing (icons in the tree) see screenshot, and it ssems as if some info is missing...

Does not work in InternetExplorer.

post-5062-0-99519500-1429380730_thumb.jp

Edited by Allow2010

Share this post


Link to post
Share on other sites

html version works in firefox but some pictures are missing (icons in the tree) see screenshot, and it ssems as if some info is missing...

Does not work in InternetExplorer.

 

As well as some of us say, sometimes documenting is harder than programming :blink:

HelpMaker really 'forgot' to put a folder with the graphics used on the page. Luckly I've found this folder on Google. So here is the updated version:

TCPServer HTML Help.rar


My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites

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

@Jefrey

Again Thank you for your UDF.

For me there are still symbols missing in the new version oft html help.

If you find a way, i (personally, maybe others see it different) would prefer a working chm file.

Also i would like to have headers for every function in the code explaining parameters, returncodes and what the function does if you are willing to write them...most functions and udfs have them...its often easier to stay in the code while learning...

Share this post


Link to post
Share on other sites

Jefrey! Excellent job and thank you for sharing!

I have a dumb question, sorry.

If _TCPServer_Start is only accepting the "port", is it possible to use a different IP Address another way? For example, exposing the server to the internet and thus needing to use the external IP address.

By the way, the help file itself works perfectly!

Thank you again!

Hi guys/girls!

I'm gonna share this UDF I made today.

It allows you to easily create TCP servers and set actions depending on three events: OnConnect, OnDisconnect and OnReceive.

It is also multi client (you can set the clients limit) and you can also bind a Console-based executable to the socket (similar to -e parameter in NetCat). This feature is useful if you want to use some Console UDF to create your TCP server and don't want to mix it with the TCP functions. Also, as it runs on background just firing events, it won't pause your script while listening/receiving, so you can do anything else (stop and restart the server, allow the user to click buttons or just wait on an infinite loop) that your callbacks will be called once the event is fired.

It's also very easy to use. See this examples:

The limit is your imagination? Well, no sure. We have this limit:

  • You can't create more than one server with this UDF in the same script. However, you can pause and resume (read 'stop and start again') your server at any time in your script, without having to reset the server settings. And of course you can have many clients (or just one, it's your choice!) in the same server.

Functions list:

_TCPServer_Start

_TCPServer_Stop

_TCPServer_Close

_TCPServer_Send

_TCPServer_Broadcast

_TCPServer_SetParam

_TCPServer_BindAppToSocket

_TCPServer_SendToBound

_TCPServer_UnBindAppToSocket

_TCPServer_GetMaxClients

_TCPServer_IsServerActive

_TCPServer_ListClients

_TCPServer_OnConnect

_TCPServer_OnDisconnect

_TCPServer_OnReceive

_TCPServer_SetMaxClients

_TCPServer_DebugMode

_TCPServer_AutoTrim

_TCPServer_SocketToIP

_TCPServer_SocketToConnID

_TCPServer_ConnIDToSocket

 

Help file and more examples included!

Latest version: 1.0

attachicon.gifTCPServer UDF.zip

Note: if the CHM help file does not work for you, use the HTML version below and run index.hta or index.htm.

HTML help.rar

Edited by coffeeturtle

Share this post


Link to post
Share on other sites

By the way, the help file itself works perfectly!

 

Hmm, i tried again on win8 and win7 and for me the helpfile does not work...only the tree comes up, but no text on the right side...

Share this post


Link to post
Share on other sites

Hmm, i tried again on win8 and win7 and for me the helpfile does not work...only the tree comes up, but no text on the right side...

 

Sorry to ask you this basic question, but do you have all of the files unzipped to one folder? Launching Help.chm from within that folder with all of the files should be good. Otherwise, index.hta would probably be the best option.

Share this post


Link to post
Share on other sites

Help FIle not working for me (Win8.1 X64)

it opens, and i get a tree with all functions, but no text and the name is still TCPMaker, which might have been a working title

 

Did you unzip Zip archive , or you just click on downloaded zip file which as I suspect opens in Explorer, and did you open this CHM directly from Zip archive ?


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

Thanks for your idea, i rechecked and found the problem:

I unpacked to my NAS and so i started the chm from an undc path myservermysharefileshelp.chm

Never had this with precompiled chm files...maybe this is because you reference some files from inside the chm and they can not be found on und path.

This seems to be a problem...from a alocal folder the chm works fine. Sorry for causing troubles...

Share this post


Link to post
Share on other sites

This is IExplorer security issue.

Edit: 

This is related to: security zones

Edited by mLipok

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

Func __TCPServer_Accept()
    If $__TCPServer_Sockets[0] >= $_TCPServer_MaxClients Then
        ;Return
    EndIf
    $accept = TCPAccept($__TCPServer_MainSocket)
    If $accept = -1 Then Return
    For $i = 1 To $_TCPServer_MaxClients
        If $__TCPServer_Sockets[$i] = 0 Then ; socket is empty
            $__TCPServer_Sockets[$i] = $accept
            $__TCPServer_Sockets[0] += 1
            $__TCPServer_SocketCache[$i][0] = $accept
            $__TCPServer_SocketCache[$i][1] = _TCPServer_SocketToIP($accept)
            If $_TCPServer_DebugMode Then __TCPServer_Log("Client " & _TCPServer_SocketToIP($accept) & " connected to socket " & $accept)
            Call($_TCPServer_OnConnectCallback, $__TCPServer_Sockets[$i], _TCPServer_SocketToIP($__TCPServer_Sockets[$i]))
            Return 0
        EndIf
    Next
EndFunc   ;==>__TCPServer_Accept

i think the ;retrun must be uncommented...else the maxlients limit is ignored...?!

Share this post


Link to post
Share on other sites

Hi, sflr, I've been busy with some things in college. Good to see that your problem was solved,  @Allow2010! Thanks for those who helped! As soon as I get some time again, I'll document it on the UDF itself (each function).

@coffeeturtle,

If _TCPServer_Start is only accepting the "port", is it possible to use a different IP Address another way? For example, exposing the server to the internet and thus needing to use the external IP address.

Yes! By default, _TCPServer_Start will listen on 0.0.0.0, which, theoretically, will listen in any interface. But if you want to listen in other interface, like the external IP, just pass it as second (optional) parameter:

#include <Inet.au3>
#include "TCPServer.au3"

_TCPServer_Start(8081, _GetIP())

; or 

_TCPServer_Start(8082, '127.0.0.1')

_TCPServer_Start(8083, 'mydomain.no-ip.com')

Of course there are other questions to consider, like if the port is visible to the internet (open and redirected to the host in the router).

@Allow2010,

 think the ;retrun must be uncommented...else the maxlients limit is ignored...?!

Damn... how could it pass in front of me... I commented it for debugging while developing it. It must be uncommented, you're right. I must upload the patched version ASAP to the original post. Thanks for pointing it!

Edit: UDF updated on the original post!

Edited by Jefrey

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites
Posted (edited)

@Jefrey Thank you for the excellent work & sharing!

FYI, I'm working on a project that makes a Socket Relay, it receives data from clients (for example, 2 clients) then pass received data to destinations (e.g 3)

I have one question related to the TCPRcv

Func __TCPServer_Recv()
    For $i = 1 To $_TCPServer_MaxClients
        If ($__TCPServer_Sockets[$i] = 0) Then ContinueLoop ;If socket is not exist then move to the next entry

        Dim $sData
        $recv = TCPRecv($__TCPServer_Sockets[$i], 1000000)
        If @error = 10054 Then ; Disconnected by user
            __TCPServer_KillConnection($i)
            ContinueLoop
        EndIf

        If $recv Then
            $sData = $recv
            Do
                $recv = TCPRecv($__TCPServer_Sockets[$i], 1000000)
                $sData &= $recv
            Until $recv = ""
            If $_TCPServer_AutoTrim Then
                $sData = StringStripWS($sData, 1 + 2)
            EndIf
            If $_TCPServer_DebugMode Then __TCPServer_Log("Client " & _TCPServer_SocketToIP($__TCPServer_Sockets[$i]) & " sent " & $sData)
            Call($_TCPServer_OnReceiveCallback, $__TCPServer_Sockets[$i], _TCPServer_SocketToIP($__TCPServer_Sockets[$i]), $sData, $__TCPServer_Pars[$i])
            
        EndIf
    Next
EndFunc   ;==>__TCPServer_Recv

May I ask, after getting data from $recv = TCPRecv($__TCPServer_Sockets[$i], 1000000)

you call another TCPRecv($__TCPServer_Sockets[$i], 1000000) until it has no data.
What does this thing do?
If I remove the Do...Util block, does it has any risk?

Edited by LukeLe
add full function __TCPServer_Recv

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

  • Similar Content

    • By Colduction
      Hello Guys and AutoIt Scriptwriters!🎉❤️
      I've created a script to notify to me if RDP main IP changed then send a message via Telegram bot to me
      But some of my RDP's Main IP are @IPAddress1 or @IPAddress3 or Public IP Address...
      I want to detect automatically the IP that windows client can run RDP to remotely control
      This image can help you that what i say, there are three RDP with specified IP, i want to run script in these RDP's then capture those IP's changes then notify me via Telegram bot

    • By rudi
      Hello,
      When new versions e.g. of your compiled script cannot be replaced on the server, as they are in use, you can use this script to manage to close the open handles and to replace the old file with your new version.

      ; Autoit v3.3.14.5 #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Res_Description=Close OpenFileHandlles, replace file on Server with a new version #AutoIt3Wrapper_Res_Fileversion=1 #AutoIt3Wrapper_Res_LegalCopyright=(c) 2019 by Rudolf Thilo, IT-Beratung Rudolf Thilo #AutoIt3Wrapper_Res_SaveSource=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #include <GUIConstantsEx.au3> #include <NetShare.au3> #include <WindowsConstants.au3> #include <Array.au3> #include <EditConstants.au3> ; Enumerate open files on the server $DragDropOpenFile = "<drag-drop file locked on Server to be closed and replaced>" $DragDropNewFile = "<drag-drop file to replace the one on the server>" $NewFile = "" $Gui_h = 250 $Gui_w = 800 $vDist = 7 ; GUICreate($GuiTitle, $w, $h, @DesktopWidth - $w - 100, @DesktopHeight - $h - 60, -1, $WS_EX_ACCEPTFILES) ; generally enable drag-drop for files into other GUI controls $myGui = GUICreate("force close of all NETWORK opened file handles", $Gui_w, $Gui_h, 100, 100, -1, $WS_EX_ACCEPTFILES) $InputFileToClose = GUICtrlCreateInput($DragDropOpenFile, 20, $vDist, $Gui_w - 40, 20) GUICtrlSetState(-1, $GUI_DROPACCEPTED) ; allow drag-droping files for this control, $InputFile Opt("Guicoordmode", 2) $InputFileNew = GUICtrlCreateInput($DragDropNewFile, -1, $vDist) GUICtrlSetState(-1, $GUI_DROPACCEPTED) ; allow drag-droping files for this control, $InputFile GUICtrlSetState(-1, $GUI_DISABLE) $lServer = GUICtrlCreateLabel("<server>", -1, $vDist) $lShare = GUICtrlCreateLabel("<share>", -1, $vDist) $lPath = GUICtrlCreateLabel("<path>", -1, $vDist) $lFile = GUICtrlCreateLabel("<file>", -1, $vDist) $doit = GUICtrlCreateButton("search for and close open file handles", -1, $vDist) GUICtrlSetState(-1, $GUI_DISABLE) $exit = GUICtrlCreateButton("cancel", -1, $vDist) GUISetState() $FN = False $FNnew = "" $FNmatch = False $ToolTitle = "" $ToolTxt = "" While 1 $input = GUICtrlRead($InputFileToClose) If $input <> $DragDropOpenFile Then ; da wurde was reingezogen $DragDropOpenFile = $input If StringLeft($input, 2) = "\\" Then $Type = "UNC" $ServerShareUNC = StringLeft($input, StringInStr($input, "\", 0, 4) - 1) $fRelPathFN = StringReplace($input, $ServerShareUNC, "") $fPath = StringLeft($fRelPathFN, StringInStr($fRelPathFN, "\", 0, -1)) $FN = StringTrimLeft($fRelPathFN, StringInStr($fRelPathFN, "\", 0, -1)) ElseIf StringMid($input, 2, 1) = ":" Then ; Pfad mit Laufwerksbuchstabe, evtl. Netzwerk Mapping (erforderlich) $drive = StringLeft($input, 2) $Type = DriveGetType($drive) If $Type = "Network" Then $ServerShareUNC = DriveMapGet($drive) $foo = StringReplace($input, $drive, $ServerShareUNC) ; Laufwerkspfad in UNC Pfad umwandeln $fRelPathFN = StringReplace($foo, $ServerShareUNC, "") $fPath = StringLeft($fRelPathFN, StringInStr($fRelPathFN, "\", 0, -1)) $FN = StringTrimLeft($fRelPathFN, StringInStr($fRelPathFN, "\", 0, -1)) Else MsgBox(0, @ScriptLineNumber, "This script can *ONLY* close open file handles on NETWORK SHARES!" & @CRLF & _ $input & @CRLF & _ $drive & " = " & $Type) ContinueLoop 2 EndIf EndIf $Server = StringLeft($ServerShareUNC, StringInStr($ServerShareUNC, "\", 0, 3) - 1) $Share = StringTrimLeft($ServerShareUNC, StringInStr($ServerShareUNC, "\", 0, 3) - 1) GUICtrlSetData($lServer, $Server) GUICtrlSetData($lShare, $Share) GUICtrlSetData($lPath, $fPath) GUICtrlSetData($lFile, $FN) GUICtrlSetState($doit, $GUI_ENABLE) GUICtrlSetState($InputFileNew, $GUI_ENABLE) EndIf If $NewFile <> GUICtrlRead($InputFileNew) Then $NewFile = GUICtrlRead($InputFileNew) If $NewFile <> $DragDropNewFile Then If StringInStr($NewFile, $DragDropNewFile) Then $NewFile = StringReplace($NewFile, $DragDropNewFile, "") GUICtrlSetData($InputFileNew, $NewFile) EndIf $FNnew = StringTrimLeft($NewFile, StringInStr($NewFile, "\", 0, -1)) If $FN = $FNnew Then If $FNmatch = False Then $FNmatch = True GUICtrlSetData($doit, "Search for open file handles, close them, overwrite old file.") EndIf Else If $FNmatch Then $FNmatch = False GUICtrlSetData($doit, "Search for open file handles and close them.") GUICtrlSetData($InputFileNew,$DragDropNewFile) EndIf EndIf EndIf EndIf Switch GUIGetMsg() Case $exit, $GUI_EVENT_CLOSE GUIDelete($myGui) Exit Case $doit AbArbeiten($Server, $Share, $fPath, $FN) EndSwitch WEnd Func AbArbeiten($_Srv, $_Shr, $_fPth, $_fNme) Local $iID = 0 Local $iRights = 1 Local $iLckCount = 2 Local $iFPFN = 3 Local $iUser = 4 ConsoleWrite($_fPth & $_fNme & @CRLF) Local $aFile = _Net_Share_FileEnum($_Srv) If IsArray($aFile) Then ; _ArrayDisplay($aFile) Local $x $ToolTxt = "Open Handles:" $ToolTitle = $aFile[0][0] & " handles still waiting to be checkt..." UpdateToolTip() AdlibRegister(UpdateToolTip, 1000) For $x = $aFile[0][0] To 1 Step -1 $ToolTitle = $x & " handles waiting to be checked..." If Not StringInStr($aFile[$x][$iFPFN], $_fPth & $_fNme) Then ; ConsoleWrite("Nix Enthalten in: " & $aFile[$x][$iFPFN] & @CRLF) _ArrayDelete($aFile, $x) Else $ToolTxt &= @CRLF & $aFile[$x][$iFPFN] & ", User = " & $aFile[$x][$iUser] ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $ToolTxt = ' & $ToolTxt & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console EndIf Next $aFile[0][0] = UBound($aFile) - 1 _ArraySort($aFile, 0, 1, 0, $iUser) ; _ArrayDisplay($aFile, $aFile[0][0] & " FileLocks found.") If $aFile[0][0] = 0 Then $ToolTitle = "Done. No open handles coud be found." $ToolTxt &= @CRLF & "Nothing to be closed!" Sleep(2000) $ToolTxt = "" Else $ToolTitle = $aFile[0][0] & " Handles found to be closed..." $CloseErr = 0 For $x = 1 To $aFile[0][0] If _Net_Share_FileClose($Server, $aFile[$x][$iID]) Then $ToolTxt &= @CRLF & @TAB & "Handle closed: " & $aFile[$x][$iID] Else $ToolTxt &= @CRLF & "ERROR: Handle Close Failed! --> " & $aFile[$x][$iFPFN] & ", User = " & $aFile[$x][$iUser] $CloseErr += 1 EndIf Next ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $CloseErr = ' & $CloseErr & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console If $CloseErr = 0 Then $ToolTitle = "Alle open handles were closed successfully." If FileExists($NewFile) Then If FileCopy($NewFile, $input, 1 + 8) Then $ToolTitle = "File could be replaced." $ToolTxt = "done" Else $ToolTitle = "File could *NOT* be replaced" $ToolTxt = "Most propably a newly open file handle was created while this script was running." & @CRLF & _ "Just start over again." EndIf EndIf Else $ToolTitle = $CloseErr & " handles could *NOT* be closed!" Sleep(2000) EndIf Sleep(1000) $ToolTxt = "" $ToolTitle = "" EndIf Else MsgBox(0, "not an array", $aFile & @CRLF & @error & @CRLF & @extended) EndIf EndFunc ;==>AbArbeiten Func UpdateToolTip() ToolTip($ToolTxt, MouseGetPos(0) + 20, MouseGetPos(1) + 20, $ToolTitle) ; ConsoleWrite( $ToolTxt & @CRLF & $ToolTitle & @CRLF & "-------------------" & @CRLF) EndFunc ;==>UpdateToolTip Rudi.
    • By Spartan117
      Hi everyone,
      I wonder if there is a cloud service that can offer a physical server so that AutoIT can turn as it is in a physical machine.
      Thank you
    • By comtech80
      Folks,
      I have an issue I've been trying to solve for a while, I'm trying to add static routes in DHCP via a 121 route rule in Windows 2012 R2 is a brutal manual process and wanted to automate this via AutoIT.
       
      When I use the "ControlGetText" everything displays properly in the MSG box but when I try and use "ControlSetText" or "ControlSend" the values won't display in the input box but the action comes back as successful?
      Anyone able to help me with this? I'm thinking this might be an active window issue but i'm not sure.
      Here is a part of my code.
       
      $hWnd = WinWait("[TITLE:Add a Static Route]","", 10)
      WinActivate($hWnd)
      $Status = ControlSend($hWnd, "", "[CLASS:Edit; INSTANCE:4]", "192"); Does not add 192 to the text box.
      Local $sTextEdit1 = ControlGetText($hWnd, "", "[CLASS:Edit; INSTANCE:1]")
      ConsoleWrite ( "ControlSend Status: " &  $Status & @CRLF); Returns a Value of 1
      ConsoleWrite ( "ControlGetText Value Edit1: " &  $sTextEdit1 & @CRLF);
       
      Please see attachment for more info.

    • By ur
      I have a button control as below screen.

      This one I am able to suppress using below code in all the OS.
      But on server 2008, sometimes the button highlighted in the image is not getting clicked and some times it is working.
      I have cross checked the IDs when it is not working, but it is working only.
       
      $win1 = "erwin Mart Configuration" $MartConfigWindow = _WinWaitActivate1($win1,"Database Details") ControlSetText($MartConfigWindow, "", "WindowsForms10.EDIT.app.0.378734a6", $dbserver) ControlSetText($MartConfigWindow, "", "WindowsForms10.EDIT.app.0.378734a4", $dbname) ControlSetText($MartConfigWindow, "", "WindowsForms10.EDIT.app.0.378734a9", $dbuser) ControlSetText($MartConfigWindow, "", "WindowsForms10.EDIT.app.0.378734a8", $dbpassword) ;Button clicl logic $iControlClickStatus = ControlClick($MartConfigWindow, "", "[CLASS:WindowsForms10.BUTTON.app.0.378734a; INSTANCE:2]") ;If above button click fails, trying with mouse click on the control if ControlFocus($MartConfigWindow, "", "WindowsForms10.BUTTON.app.0.378734a2")=1 then ;sometimes above button fails in win server 2008,so this loop Send("{ENTER") EndIf  
      Any suggestion on how to resolve this.?
×
×
  • Create New...