tarretarretarre

Socket-IO - An event-driven TCP UDF (Realtime chat example)

15 posts in this topic

#1 ·  Posted (edited)

AutoIt-SocketIo

Yep yep, this is pretty much an attempt to port the existing project's concept https://socket.io/ to AutoIt's Codebase. So i will not go in to so much detail.

Features

  • Easy API
  • VarType Translation (Example: If the server sends an int, the client will receive an int and vice versa)
  • Fully featured examples
  • Data encryption (Using Autoit's UDF Crypt.au3)

Limitations / Drawbacks

  • Every Broadcast/Emit is limited to a maximum of 16 parameters
  • Every Callback Function has to have the same number of parameters as the Broadcasted/Emited event
  • It is not possible to Broadcast/Emit objects
  • Only 1D-arrays are allowed to be Broadcasted/Emitted (2D arrays will probably never be supported)

Changelog

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.

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

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)

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

Api methods

Server methods

  • _Io_Listen($iPort, $iAddress = @IPAddress1, $iMaxPendingConnections = Default, $iMaxDeadSocketsBeforeTidy = 1000, $iMaxConnections = 100000)

Listens for incomming connections. Returns a SocketID. If $iMaxDeadSocketsBeforeTidy is set to False, you have to manually invoke _Io_TidyUp to get rid of dead sockets. If the iMaxConnections + 1 client connects, they will be instantly disconnected.

  • _Io_Subscribe(ByRef $socket, $sRoomName)

Subscribes socket to a room. Returns nothing. To emit to these subscriptions see _Io_BroadcastToRoom.

  • _Io_Unsubscribe(ByRef $socket, $sRoomName = null)

Unsubscribes a socket from a room. Returns nothing. If $sRoomName is null, every subscription will expire

  • _Io_Broadcast(ByRef $socket, $sEventName, $p1, $p2, ...$p16)

 

Emits an event to all connected sockets besides the originator. Returns nothing.
  • _Io_BroadcastToAll(ByRef $socket, $sEventName, $p1, $p2, ...$p16)

Emits an event to all connected sockets. Returns nothing. $socket is ignored in this function

  • _Io_BroadcastToRoom(ByRef $socket, $sDesiredRoomName, $sEventName, $p1, $p2, ...$p16)

Emits an event to all connected sockets in the given room name. Returns nothing. See more at _Io_Subscribe

  • _Io_socketGetProperty(ByRef $socket, $sProp = Default)

Retrieves information about the socket. Returns Array || String. Default = Array of all properties. Available properties: "ip", "date".

  • _Io_getSockets($bForceUpdate = False, $socket = $__g_io_mySocket, $whoAmI = $__g_io_whoami)

Returns all stored sockets, [$i + 0] = socket, [$i + 1] = ip, [$i + 2] = Date joined (YYYY-MM-DD HH:MM:SS) Ubound wont work propery with this array, so use The $aArr[1] element to retrive the size. For $i = 1 to $aArr[1] step +3 ....... the socket is (Keyowrd) "Null" if the socket is dead.

  • _Io_getDeadSocketCount()

Returns the number of all dead sockets.

  • _Io_getSocketsCount()

Returns the number of all sockets (Regardless of state).

  • _Io_getActiveSocketCount()

Returns the number of all active connections.

  • _Io_getMaxConnections()

Returns the maximum allowed connections.

  • _Io_getMaxDeadSocketsCount()

Returns the maximum allowed dead connections before _Io_TidyUp() is invoked.

  • _Io_getBanlist($iEntry = Default)

Returns an array of the whole banlist. If $iEntry is set to any number but Default the data for that entry will be retuned instead.

  • _Io_Ban($socketOrIp, $nTime = 3600, $sReason = "Banned", $sIssuedBy = "system")

Ip ban and prevent incomming connections from a given socket \ ip. Returns True all the time. If a $socket is passed, the ip will be retrived from the socket and the client will be disconnected, upon reconnecting, the banned event will be emitted to the banned client (If they still are banned)

  • _Io_Sanction($socketOrIp)

Removes a previous banned ip address. Returns True if the ban was removed, returns False if the ip could not be found. If a $socket is passed, the ip will be retrived from the socket.

  • _Io_IsBanned($socketOrIp)

Checks if an ip exists in the banlist Returns the $index of the banned ip if found, returns false if not found. If a $socketis passed, the ip will be retrived from the socket.

  • _Io_TidyUp()

Re-builds array of active sockets. Returns nothing. Only use this function if $iMaxDeadSocketsBeforeTidy i set to False

Client methods

  • _Io_Connect($iAddress, $iPort, $bAutoReconnect = True)

Attempts to connect to a Server Returns a SocketID. if $bAutoReconnect is set to False. You must use _Io_Connect or _Io_Reconnect to establish a new connection

  • _Io_Reconnect(ByRef $socket)

Attempts to reconnect to the server Returns a SocketID. This function is invoked automatically if $bAutoReconnect is set to True.

Server and Client methods

  • _Io_setEventPreScript($fCallback)

The callback defined for this function will be ran before an event takes place Returns nothing. The callback requires exactly two parameters $sEventName and $sEventFuncName

  • _Io_setEventPostScript($fCallback)

The callback defined for this function will be ran before an event takes place Returns nothing. The callback requires exactly two parameters $sEventName and $sEventFuncName

  • _Io_getVer()

Returns the current (semantic version)[http://semver.org/] of the UDF

  • _Io_On(Const $sEventName, Const $fCallback, $socket = $__g_io_mySocket)

Binds an event. Returns nothing. $fCallback has to be an actual function reference. No strings!

  • _Io_Emit(ByRef $socket, $sEventName, $p1, $p2, ...$p16)

Emits an event to the given socket. Returns nothing. Only 1D-Arrays, Ints, Floats, Doubles, Ptrs, Binarys, Strings, Null-keywords or Bools should be used as parameters.

  • _Io_Loop(ByRef $socket, $whoAmI = $__g_io_whoami)

The event engine. Returns a bool. Should only be used as the main While loop. The function will return false if the function _Io_Disconnect is invoked

  • _Io_LoopFacade()

A substitute for the _Io_Loop solution. Returns nothing. Should only be used with AdlibRegister. If _Io_Disconnect is invoked, this facade will also be un-registered. This function will not work properly if more than 1 _Io_Connect or _Io_Listen exists in the same script.

  • _Io_EnableEncryption($sFileOrKey, $CryptAlgId = $CALG_AES_256)

Encrypts data between the server and the client with the use of Autoit's Crypt.au3. Returns true if successfully configured, else @error is set. The encryption has to be enabled on both sides for it to work.

  • _Io_Disconnect($socket = null)

Manually disconnect as Client or server / Disconnects a client (Only when acting as server). Returns nothing. This function will purge any previously set _Io_LoopFacade and cause _Io_Loop to return false. If the $socket parameter is set when running as a server, the id of that socket will be disconnected

  • _Io_setRecvPackageSize($nPackageSize = 4096)

Sets the maxlen for TCPRecv Returns nothing. Is set default to 4096 by both the server and the client.

  • _Io_ClearEvents()

Removes all events from the script. Returngs nothing.

  • _Io_TransferSocket(ByRef $from, ByRef $to)

Transfer the socket id and events to a new Socket. Returns nothing

Default events

Server events

  • connection

Takes 1 parameter ($socket)

Client events

  • banned

Takes 5 parametsrs ($socket, $created_at, $expires_at, $sReason, $sIssuedBy)

Server and Client events

  • disconnect

Takes 1 parameter ($socket)

View source on github

 

Autoit-Socket-IO-1.0.0.zip (OLD!)

Autoit-Socket-IO-1.1.0.zip (OLD)

Autoit-Socket-IO-1.3.0.zip (OLD)

Autoit-Socket-IO-1.4.0.zip (NEWEST 2017-08-11)

Edited by tarretarretarre
Update
2 people like this

Share this post


Link to post
Share on other sites



#2 ·  Posted

It looks interesting.
I have to testify.


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
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 API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

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 * Best coding practices * 

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) * 

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: 2017-06-04

Share this post


Link to post
Share on other sites

#4 ·  Posted

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

#5 ·  Posted

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

#6 ·  Posted

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

#7 ·  Posted

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

#8 ·  Posted

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

#9 ·  Posted

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

#10 ·  Posted

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

#11 ·  Posted

Example TCP/UPD File Transfer please!


Regards,
 

Share this post


Link to post
Share on other sites

#12 ·  Posted

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 :)

1 person likes this

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

#13 ·  Posted

43 minutes ago, TheDcoder said:

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

P.S

I think you mean UDP :)

Yes UDP, and I will not ask if  i not searched and try!


Regards,
 

Share this post


Link to post
Share on other sites

#14 ·  Posted

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

#15 ·  Posted

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

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

    • timmalos
      By timmalos
      Hello all.
      In case this is interesting few of you, I share my AMCP 2.1 protocol UDF in AutoIT. This protocol is used by CasparCG server, which is a Windows and Linux software used to play out professional graphics, audio and video to multiple outputs as a layerbased real-time compositor. It has been in 24/7 broadcast production since 2006. It's free and opensource.
      The UDF I share allows communication between an AutoIt based client and the CasparCG, based on following documentation : http://casparcg.com/wiki/CasparCG_2.1_AMCP_Protocol
      If you want more details on CasparCG :  official WebSite or have a look to this video
      I'm currently building a full Client based on AutoIt, with many features like drag-and-drop layers, but sadly I can't share it right now, might come later. Don't hesitate to ask questions if you have any or need a basic example.
      The only requirement for this UDF is the other Event-driven TCP UDF by Kip
       
       

      AMCP_shared.au3
      TCP.au3
    • kingjacob90
      By kingjacob90
      Hi
      I am trying to send a file over TCP from a TCP client to server. If I run the server and client on the same computer the file is send fine, but if the server is on one computer on the network and the client on another the file is sent in what looks like more than one packet. In other words the server receives 4 msg from the client.
      Why is this, how do I make it send in one go, or what is a way around it?
      Side Note: TCP server has a max of 999999999
    • AlexFing17
      By AlexFing17
      i am trying to figure out how a server can connect to a client Over the internet. 
      In this is script. The client connects to the server on the same machine (localhost) and executes the commands from the client.
      How can I change that instead communicating over localhost to communicate over the internet with tcp ipaddress and a port.
       
      What i actually need help of is
      1. The server will open a port and  listen to communication from a No-ip address
      2. I input the no-ip address and correct port in the client side, and when i click on connect, it connects to the server if its online
       
       
      This is the client
      #include <GuiConstantsEx.au3> THIS IS THE CLIENT #include <NamedPipes.au3> #include <StaticConstants.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> ; =============================================================================================================================== ; Description ...: This is the client side of the pipe demo ; Author ........: Paul Campbell (PaulIA) ; Notes .........: ; =============================================================================================================================== ; =============================================================================================================================== ; Global constants ; =============================================================================================================================== Global Const $BUFSIZE = 4096 Global Const $DEFCMD = "cmd.exe /c dir c:\" Global Const $PIPE_NAME = "\\$\\pipe\\AutoIt3" Global Const $ERROR_MORE_DATA = 234 ; =============================================================================================================================== ; Global variables ; =============================================================================================================================== Global $g_idEdit, $g_idMemo, $g_idSend, $g_idServer, $g_hPipe ; =============================================================================================================================== ; Main ; =============================================================================================================================== CreateGUI() MsgLoop() ; =============================================================================================================================== ; Creates a GUI for the client ; =============================================================================================================================== Func CreateGUI() Local $hGUI = GUICreate("FarC0nn3c7", 500, 400, -1, -1, $WS_SIZEBOX) GUICtrlCreateLabel("Server:", 2, 14, 52, 20, $SS_RIGHT) $g_idServer = GUICtrlCreateEdit("<local>", 56, 10, 200, 20, $SS_LEFT) GUICtrlCreateLabel("Command:", 2, 36, 52, 20, $SS_RIGHT) $g_idEdit = GUICtrlCreateEdit($DEFCMD, 56, 32, 370, 20, $SS_LEFT) $g_idSend = GUICtrlCreateButton("Pawn Dem", 430, 32, 60, 20) $g_idMemo = GUICtrlCreateEdit("", 0, 62, _WinAPI_GetClientWidth($hGUI), 332) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState() EndFunc ;==>CreateGUI ; =============================================================================================================================== ; Logs an error message to the display ; =============================================================================================================================== Func LogError($sMessage) $sMessage &= " (" & _WinAPI_GetLastErrorMessage() & ")" GUICtrlSetData($g_idMemo, GUICtrlRead($g_idMemo) & $sMessage & @CRLF) EndFunc ;==>LogError ; =============================================================================================================================== ; Logs a message to the display ; =============================================================================================================================== Func LogMsg($sMessage) GUICtrlSetData($g_idMemo, GUICtrlRead($g_idMemo) & $sMessage & @CRLF) EndFunc ;==>LogMsg ; =============================================================================================================================== ; MsgLoop ; =============================================================================================================================== Func MsgLoop() While True Switch GUIGetMsg() Case $g_idSend SendCmd() Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd EndFunc ;==>MsgLoop ; =============================================================================================================================== ; This function opens a pipe to the server ; =============================================================================================================================== Func OpenPipe() Local $sName, $sPipe ; Get pipe handle $sName = GUICtrlRead($g_idServer) If $sName = "<local>" Then $sName = "." $sPipe = StringReplace($PIPE_NAME, "$", $sName) $g_hPipe = _WinAPI_CreateFile($sPipe, 2, 6) If $g_hPipe <> -1 Then Return True LogError("OpenPipe failed") Return False EndFunc ;==>OpenPipe ; =============================================================================================================================== ; This function reads a message from the pipe ; =============================================================================================================================== Func ReadMsg() Local $bSuccess, $iRead, $pBuffer, $tBuffer $tBuffer = DllStructCreate("char Text[4096]") $pBuffer = DllStructGetPtr($tBuffer) GUICtrlSetData($g_idMemo, "") While 1 $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, 0) If $iRead = 0 Then ExitLoop If Not $bSuccess Or (_WinAPI_GetLastError() = $ERROR_MORE_DATA) Then ExitLoop GUICtrlSetData($g_idMemo, StringLeft(DllStructGetData($tBuffer, "Text"), $iRead), 1) WEnd EndFunc ;==>ReadMsg ; =============================================================================================================================== ; This function sends a command to the server ; =============================================================================================================================== Func SendCmd() If OpenPipe() Then SetReadMode() WriteMsg(GUICtrlRead($g_idEdit)) ReadMsg() _WinAPI_CloseHandle($g_hPipe) EndIf EndFunc ;==>SendCmd ; =============================================================================================================================== ; This function sets the pipe read mode ; =============================================================================================================================== Func SetReadMode() If Not _NamedPipes_SetNamedPipeHandleState($g_hPipe, 1, 0, 0, 0) Then LogError("SetReadMode: _NamedPipes_SetNamedPipeHandleState failed") EndIf EndFunc ;==>SetReadMode ; =============================================================================================================================== ; This function writes a message to the pipe ; =============================================================================================================================== Func WriteMsg($sMessage) Local $iWritten, $iBuffer, $pBuffer, $tBuffer $iBuffer = StringLen($sMessage) + 1 $tBuffer = DllStructCreate("char Text[" & $iBuffer & "]") $pBuffer = DllStructGetPtr($tBuffer) DllStructSetData($tBuffer, "Text", $sMessage) If Not _WinAPI_WriteFile($g_hPipe, $pBuffer, $iBuffer, $iWritten, 0) Then LogError("WriteMsg: _WinAPI_WriteFile failed") EndIf EndFunc ;==>WriteMsg  
      And this is the server
      #include <GuiConstantsEx.au3> #include <NamedPipes.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> #NoTrayIcon ; =============================================================================================================================== ; Description ...: This is the server side of the pipe demo ; Author ........: Paul Campbell (PaulIA) ; Notes .........: ; =============================================================================================================================== ; =============================================================================================================================== ; Global constants ; =============================================================================================================================== Global Const $DEBUGGING = False Global Const $BUFSIZE = 4096 Global Const $PIPE_NAME = "\\.\\pipe\\AutoIt3" Global Const $TIMEOUT = 5000 Global Const $WAIT_TIMEOUT = 258 Global Const $ERROR_IO_PENDING = 997 Global Const $ERROR_PIPE_CONNECTED = 535 ; =============================================================================================================================== ; Global variables ; =============================================================================================================================== Global $g_hEvent, $g_idMemo, $g_pOverlap, $g_tOverlap, $g_hPipe, $g_hReadPipe, $g_iState, $g_iToWrite ; =============================================================================================================================== ; Main ; =============================================================================================================================== CreateGUI() InitPipe() MsgLoop() ; =============================================================================================================================== ; Creates a GUI for the server ; =============================================================================================================================== Func CreateGUI() Local $hGUI $hGUI = GUICreate("Pipe Server", 500, 400, -1, -1, $WS_SIZEBOX) $g_idMemo = GUICtrlCreateEdit("", 0, 0, _WinAPI_GetClientWidth($hGUI), _WinAPI_GetClientHeight($hGUI)) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState() EndFunc ;==>CreateGUI ; =============================================================================================================================== ; This function creates an instance of a named pipe ; =============================================================================================================================== Func InitPipe() ; Create an event object for the instance $g_tOverlap = DllStructCreate($tagOVERLAPPED) $g_pOverlap = DllStructGetPtr($g_tOverlap) $g_hEvent = _WinAPI_CreateEvent() If $g_hEvent = 0 Then LogError("InitPipe ..........: API_CreateEvent failed") Return EndIf DllStructSetData($g_tOverlap, "hEvent", $g_hEvent) ; Create a named pipe $g_hPipe = _NamedPipes_CreateNamedPipe($PIPE_NAME, _ ; Pipe name 2, _ ; The pipe is bi-directional 2, _ ; Overlapped mode is enabled 0, _ ; No security ACL flags 1, _ ; Data is written to the pipe as a stream of messages 1, _ ; Data is read from the pipe as a stream of messages 0, _ ; Blocking mode is enabled 1, _ ; Maximum number of instances $BUFSIZE, _ ; Output buffer size $BUFSIZE, _ ; Input buffer size $TIMEOUT, _ ; Client time out 0) ; Default security attributes If $g_hPipe = -1 Then LogError("InitPipe ..........: _NamedPipes_CreateNamedPipe failed") Else ; Connect pipe instance to client ConnectClient() EndIf EndFunc ;==>InitPipe ; =============================================================================================================================== ; This function loops waiting for a connection event or the GUI to close ; =============================================================================================================================== Func MsgLoop() Local $iEvent Do $iEvent = _WinAPI_WaitForSingleObject($g_hEvent, 0) If $iEvent < 0 Then LogError("MsgLoop ...........: _WinAPI_WaitForSingleObject failed") Exit EndIf If $iEvent = $WAIT_TIMEOUT Then ContinueLoop Debug("MsgLoop ...........: Instance signaled") Switch $g_iState Case 0 CheckConnect() Case 1 ReadRequest() Case 2 CheckPending() Case 3 RelayOutput() EndSwitch Until GUIGetMsg() = $GUI_EVENT_CLOSE EndFunc ;==>MsgLoop ; =============================================================================================================================== ; Checks to see if the pending client connection has finished ; =============================================================================================================================== Func CheckConnect() Local $iBytes ; Was the operation successful? If Not _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iBytes, False) Then LogError("CheckConnect ......: Connection failed") ReconnectClient() Else $g_iState = 1 EndIf EndFunc ;==>CheckConnect ; =============================================================================================================================== ; This function reads a request message from the client ; =============================================================================================================================== Func ReadRequest() Local $pBuffer, $tBuffer, $iRead, $bSuccess $tBuffer = DllStructCreate("char Text[" & $BUFSIZE & "]") $pBuffer = DllStructGetPtr($tBuffer) $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, $g_pOverlap) If $bSuccess And ($iRead <> 0) Then ; The read operation completed successfully Debug("ReadRequest .......: Read success") Else ; Wait for read Buffer to complete If Not _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iRead, True) Then LogError("ReadRequest .......: _WinAPI_GetOverlappedResult failed") ReconnectClient() Return Else ; Read the command from the pipe $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, $g_pOverlap) If Not $bSuccess Or ($iRead = 0) Then LogError("ReadRequest .......: _WinAPI_ReadFile failed") ReconnectClient() Return EndIf EndIf EndIf ; Execute the console command If Not ExecuteCmd(DllStructGetData($tBuffer, "Text")) Then ReconnectClient() Return EndIf ; Relay console output back to the client $g_iState = 3 EndFunc ;==>ReadRequest ; =============================================================================================================================== ; This function relays the console output back to the client ; =============================================================================================================================== Func CheckPending() Local $bSuccess, $iWritten $bSuccess = _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iWritten, False) If Not $bSuccess Or ($iWritten <> $g_iToWrite) Then Debug("CheckPending ......: Write reconnecting") ReconnectClient() Else Debug("CheckPending ......: Write complete") $g_iState = 3 EndIf EndFunc ;==>CheckPending ; =============================================================================================================================== ; This function relays the console output back to the client ; =============================================================================================================================== Func RelayOutput() Local $pBuffer, $tBuffer, $sLine, $iRead, $bSuccess, $iWritten $tBuffer = DllStructCreate("char Text[" & $BUFSIZE & "]") $pBuffer = DllStructGetPtr($tBuffer) ; Read data from console pipe _WinAPI_ReadFile($g_hReadPipe, $pBuffer, $BUFSIZE, $iRead) If $iRead = 0 Then LogMsg("RelayOutput .......: Write done") _WinAPI_CloseHandle($g_hReadPipe) _WinAPI_FlushFileBuffers($g_hPipe) ReconnectClient() Return EndIf ; Get the data and strip out the extra carriage returns $sLine = StringLeft(DllStructGetData($tBuffer, "Text"), $iRead) $sLine = StringReplace($sLine, @CR & @CR, @CR) $g_iToWrite = StringLen($sLine) DllStructSetData($tBuffer, "Text", $sLine) ; Relay the data back to the client $bSuccess = _WinAPI_WriteFile($g_hPipe, $pBuffer, $g_iToWrite, $iWritten, $g_pOverlap) If $bSuccess And ($iWritten = $g_iToWrite) Then Debug("RelayOutput .......: Write success") Else If Not $bSuccess And (_WinAPI_GetLastError() = $ERROR_IO_PENDING) Then Debug("RelayOutput .......: Write pending") $g_iState = 2 Else ; An error occurred, disconnect from the client LogError("RelayOutput .......: Write failed") ReconnectClient() EndIf EndIf EndFunc ;==>RelayOutput ; =============================================================================================================================== ; This function is called to start an overlapped connection operation ; =============================================================================================================================== Func ConnectClient() $g_iState = 0 ; Start an overlapped connection If _NamedPipes_ConnectNamedPipe($g_hPipe, $g_pOverlap) Then LogError("ConnectClient .....: ConnectNamedPipe 1 failed") Else Switch @error ; The overlapped connection is in progress Case $ERROR_IO_PENDING Debug("ConnectClient .....: Pending") ; Client is already connected, so signal an event Case $ERROR_PIPE_CONNECTED LogMsg("ConnectClient .....: Connected") $g_iState = 1 If Not _WinAPI_SetEvent(DllStructGetData($g_tOverlap, "hEvent")) Then LogError("ConnectClient .....: SetEvent failed") EndIf ; Error occurred during the connection event Case Else LogError("ConnectClient .....: ConnectNamedPipe 2 failed") EndSwitch EndIf EndFunc ;==>ConnectClient ; =============================================================================================================================== ; Dumps debug information to the screen ; =============================================================================================================================== Func Debug($sMessage) If $DEBUGGING Then LogMsg($sMessage) EndFunc ;==>Debug ; =============================================================================================================================== ; Executes a command and returns the results ; =============================================================================================================================== Func ExecuteCmd($sCmd) Local $tProcess, $tSecurity, $tStartup, $hWritePipe ; Set up security attributes $tSecurity = DllStructCreate($tagSECURITY_ATTRIBUTES) DllStructSetData($tSecurity, "Length", DllStructGetSize($tSecurity)) DllStructSetData($tSecurity, "InheritHandle", True) ; Create a pipe for the child process's STDOUT If Not _NamedPipes_CreatePipe($g_hReadPipe, $hWritePipe, $tSecurity) Then LogError("ExecuteCmd ........: _NamedPipes_CreatePipe failed") Return False EndIf ; Create child process $tProcess = DllStructCreate($tagPROCESS_INFORMATION) $tStartup = DllStructCreate($tagSTARTUPINFO) DllStructSetData($tStartup, "Size", DllStructGetSize($tStartup)) DllStructSetData($tStartup, "Flags", BitOR($STARTF_USESTDHANDLES, $STARTF_USESHOWWINDOW)) DllStructSetData($tStartup, "StdOutput", $hWritePipe) DllStructSetData($tStartup, "StdError", $hWritePipe) If Not _WinAPI_CreateProcess("", $sCmd, 0, 0, True, 0, 0, "", DllStructGetPtr($tStartup), DllStructGetPtr($tProcess)) Then LogError("ExecuteCmd ........: _WinAPI_CreateProcess failed") _WinAPI_CloseHandle($g_hReadPipe) _WinAPI_CloseHandle($hWritePipe) Return False EndIf _WinAPI_CloseHandle(DllStructGetData($tProcess, "hProcess")) _WinAPI_CloseHandle(DllStructGetData($tProcess, "hThread")) ; Close the write end of the pipe so that we can read from the read end _WinAPI_CloseHandle($hWritePipe) LogMsg("ExecuteCommand ....: " & $sCmd) Return True EndFunc ;==>ExecuteCmd ; =============================================================================================================================== ; Logs an error message to the display ; =============================================================================================================================== Func LogError($sMessage) $sMessage &= " (" & _WinAPI_GetLastErrorMessage() & ")" ConsoleWrite($sMessage & @LF) EndFunc ;==>LogError ; =============================================================================================================================== ; This function is called when an error occurs or when the client closes its handle to the pipe ; =============================================================================================================================== Func ReconnectClient() ; Disconnect the pipe instance If Not _NamedPipes_DisconnectNamedPipe($g_hPipe) Then LogError("ReconnectClient ...: DisonnectNamedPipe failed") Return EndIf ; Connect to a new client ConnectClient() EndFunc ;==>ReconnectClient  
    • VIP
      By VIP
      Use: 
       
      Server Script:
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> #include <GuiEdit.au3> #include <GuiStatusBar.au3> #include <MsgBoxConstants.au3> #include <ScrollBarsConstants.au3> #include <WindowsConstants.au3> #include "TCP.au3" OnAutoItExitRegister("_OnExit") Func _OnExit() TCPShutdown() Exit EndFunc ;==>_OnExit #Region Global $hGUI = GUICreate("TCP AutoIT Server", 620, 400, -1, -1, -1, BitOR($WS_EX_ACCEPTFILES, $WS_EX_TOPMOST, $WS_EX_WINDOWEDGE)) Global $sMode = GUICtrlCreateRadio("Server Mode", 16, 8, 97, 17) GUICtrlSetState(-1, $GUI_CHECKED) Global $sGlobalIP = GUICtrlCreateInput("", 170, 8, 120, 21, $ES_READONLY) Global $sServerIP = GUICtrlCreateInput(@IPAddress1, 300, 8, 120, 21, $ES_READONLY) Global $sServerPORT = GUICtrlCreateInput("8888", 425, 8, 39, 21) GUICtrlCreateLabel("IP Server:", 120, 10, 51, 17) Global $bStartServer = GUICtrlCreateButton("Start Server", 512, 6, 89, 33) Global $gMessenger = GUICtrlCreateGroup("Text to Send", 8, 64, 601, 129) Global $tMessenger = GUICtrlCreateEdit("", 15, 85, 489, 97, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "[START]kYtkjq1VuPTdNQtNlLuzUcEA56F4AaxlrhPZ3FSMd9Svss6Fflt0au6GMqMukNudNX02q7VqFVqJaaD0m5GG7hkGhg6TvblZDCZJ2YZNS1lj4t0hSmBly0nMBQYPDc3XTCUD3o4hZnROywXgaw713XHEeiuiXvu6UVXkVvlSdSlox8OkgEu0pk9zKYQJM0nfiiEaCbo4Rp6qKdDsVCtuDgQSmgsXbI5ZIV2kq59AGkX52Zy6OvH2gRuMZeW3ub0aFr9r2c2XpcNOc1FPWcMfHsk77fk8GkYrtLTAYhFt2kzKLS0KKUiVaymVXMcgGhIpeAGfGLt9RSnfgBFMxUzLWMr031ts48toWug85ktsJmdfN9uqHUNGkIEY2pOFNN88PuAqqmoaSit3TvHZgyai7v1XubxaS4G2pK5hB2uhC0rljehCjMo5TRNiOdXvrLELgTT2ema8FbPZoNT4Vs3nb6dYTok7wloUbpK6ggWkHfjG6sAQJItNYPhRdVcB2YqnBbT8hreFoQXy2YAtbtLmRWTbNFvxyiSdn0yK92b4VJT4hIa5UjRkkQ43qwZBIpw5cfhXRXUm7sH6UNiTnLSC4jtFaphrXNSjVsaphMjVi573JjWCIBzTsjxW4PZe7doa7fgilh1gN9CQySFsSzhxGbGMWRqh8wuAEih7CogXIs7YaTq1NQpjLTkTAmcL0HPVYToWnR6D1xyFVUa3hZ8JvUF5bLel84Dljn57NO0ou60O2D6akQ6FuzOnO4cjyLGjvFamVHCanXJlx8paI3DTIT2NluMOtYnk0wyVjcrQlP2b9D63r7th2kH1SAe7vrqh0sIEHqmqho6IoiLSaB19buKuMFP1HViXSxsbsncElZrVwRKQVzPEb9NiqFAjjR7gXuQwMw1knmCvJZyNgmJPaFys0QqmylanmWt6QmH6JiaryIGW8QAxup14BQBCja46SSt8iVvhK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PMSJWceEl222WTTTZffSge7yj5tU28b84DaMaOGZ8xFXSAqbyRpk6JIhRU7QutwXyCXRf8fbW4MjvNh2Fd7zaLnslD5MYN1g1ZSeqZSnpMnoZoarJSmlMKWVBm3TnlrFc3yHufYsUxJo1qP1hGQmZW9uoMjHVDZvDGiKxaxkkjZaM7U4nkSIh4sJjVkrXQFo7wwldEOJ4R9AgO5YRJimvkN6uXWKYbk7PLrY5Hon5htSbWy44l5TScsHSsmVT1hbJviIdHRvRMVbyPInafJPlQv2y1PKfwuyJIapYMQxNUPo1rOqFFpkMoHWIzCODK9IpUVYpFZE4JEhT5pnqTeRJxmrxvb4EuPGgd2jarO4aV05wKkjnmVSkpcurW7oZU6oEXRCqEzKXMGY4oBc8LbsZ4LMsVy2va1qpINqHQ3XBMO2FTDMUQIVL6ZKVCbiRHkSZbcb0YMjbneHvqjA8OxwhBIVJHR2u88hEeCPLnC6Aldtj8MStYd2MVX84JAbg2Ex9Z3xZ0e2XZQJLxKRIRq1AsZOe7s5HuIrbCNZIxzevnTPSMlhMilYrYbmQ3AmybdT20k0l99ELTVoU6tQeliov8LxEwpIgykKNSacSGBwayT0gH0EZpASsrs3rsv29NEOJzXtz94OgLiQU5BiZ5VyVl4MI4IPKyPvlog4LVgFV2qZSty9x9VXfeWTm8zxKOaBR1RV8Hi1sRw1peADLASmvCi9lQWWUw8fFFCAe5dUMhmrWGM8gGP919gKnqylw9GAl07pko9w1R6G3S1vKbvdjD9gSNXLQVf4M1G1CrfuHplDBZFGmfMrFA6uqZGptSZS2Kb4WZFCvkbcHgdDUlp2L05Oo7UhEJKhUs7hd[END]") Global $bSendMes = GUICtrlCreateButton("SEND", 511, 83, 89, 105) GUICtrlCreateGroup("", -99, -99, 1, 1) GUICtrlCreateLabel("File To Send:", 16, 200, 80, 17) Global $sPathFileSend = GUICtrlCreateInput(@TempDir & "\XXX.jpg", 104, 200, 361, 21) Global $bSelectFile = GUICtrlCreateButton(".!.", 472, 200, 35, 25) GUICtrlCreateLabel("Path To Save:", 16, 230, 80, 17) Global $sPathFileSave = GUICtrlCreateInput(@DesktopDir, 104, 230, 361, 21) Global $bSelectDir = GUICtrlCreateButton("...", 472, 230, 35, 25) Global $bSendFile = GUICtrlCreateButton("Send File", 512, 195, 89, 60) ;~ Global $tStatus = GUICtrlCreateLabel("", 16, 45, 580, 17) Global $tStatus = GUICtrlCreateLabel("List Client:", 36, 45, 60, 17) Global $listClient = GUICtrlCreateCombo("", 100, 45, 500, 17) Global $gReceived = GUICtrlCreateGroup("Received", 8, 266, 601, 129) Global $cDataReceived = GUICtrlCreateEdit("", 16, 282, 585, 105, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "") GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) #EndRegion Global $hClient, $xSocket, $xServerIP, $xServerPORT, $xPathFileSend, $xPathFileSave, $xGlobalIP = GetIP() GUICtrlSetData($sGlobalIP, $xGlobalIP) _WriteLog("Server IP WAN: " & $xGlobalIP) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $bStartServer _WriteLog("SERVER: Starting up server...") $xServerIP = GUICtrlRead($sServerIP) $xServerPORT = GUICtrlRead($sServerPORT) _WriteLog("Server IP: " & $xServerIP) _WriteLog("Server Port: " & $xServerPORT) $hServer = _TCP_Server_Create($xServerPORT, "0.0.0.0") _TCP_RegisterEvent($hServer, $TCP_NEWCLIENT, "NewClient") _TCP_RegisterEvent($hServer, $TCP_DISCONNECT, "Disconnect") _TCP_RegisterEvent($hServer, $TCP_RECEIVE, "Recieved") _WriteLog( "SERVER: Started") GUICtrlSetData($bStartServer, "Running") GUICtrlSetState($bStartServer, $GUI_DISABLE) Case $bSendFile ConsoleWrite("Send File Pressed!" & @CRLF) Case $bSendMes Local $sClient = GUICtrlRead($listClient) $xMessenger = GUICtrlRead($tMessenger) _TCP_Send($sClient, $xMessenger) ConsoleWrite("Send Messenger Pressed!" & @CRLF) Case $bSelectFile $xPathFileSend = FileOpenDialog("Select file to send:", @DesktopDir, "All (*.*)", 3, "", $hGUI) If Not @error Then GUICtrlSetData($sPathFileSend, $xPathFileSend) Case $bSelectDir $xPathFileSave = FileSelectFolder("Select local to save file received:", @DesktopDir, 0, @ScriptDir, $hGUI) If Not @error Then GUICtrlSetData($sPathFileSave, $xPathFileSave) EndSwitch Sleep(1) WEnd Func NewClient($hSocket, $iError) GUICtrlSetData($listClient, $hSocket, $hSocket) _WriteLog("SERVER: New client connected/ Socket:" & $hSocket & " /Sending this: Welcome!") _TCP_Send($hSocket, "Welcome!") EndFunc ;==>NewClient Func Received($hSocket, $sReceived, $iError) _WriteLog("CLIENT: We received from Socket: " & $hSocket & " data: " & $sReceived) EndFunc ;==>Received Func Disconnect($hSocket, $iError) _WriteLog("SERVER: Client disconnected. Socket:" & $hSocket) EndFunc ;==>Disconnect Func _WriteLog($sLogMsg) Local $OldLog = GUICtrlRead($cDataReceived) GUICtrlSetData($cDataReceived, $OldLog & @CRLF & $sLogMsg) ;~ GUICtrlSetData($tStatus, $sLogMsg) ConsoleWrite("! " & $sLogMsg & @CRLF) $iEnd = StringLen(GUICtrlRead($tMessenger)) _GUICtrlEdit_SetSel($tMessenger, $iEnd, $iEnd) _GUICtrlEdit_Scroll($tMessenger, $SB_SCROLLCARET) $iEnd = StringLen(GUICtrlRead($cDataReceived)) _GUICtrlEdit_SetSel($cDataReceived, $iEnd, $iEnd) _GUICtrlEdit_Scroll($cDataReceived, $SB_SCROLLCARET) EndFunc ;==>_WriteLog Func GetIP($i = "ip") Local $return, $IP = StringSplit(BinaryToString(InetRead("http://api.wipmania.com/")), "<br>", 1) If $i = "from" Then If Not $IP[1] = "" Then $return = $IP[2] Else Return "Error: Api not responding." EndIf Else If Not $IP[1] = "" Then $return = $IP[1] Else Return "Error: Api not responding." EndIf EndIf Return $return EndFunc ;==>GetIP Client Script:
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> #include <GuiEdit.au3> #include <GuiStatusBar.au3> #include <MsgBoxConstants.au3> #include <ScrollBarsConstants.au3> #include <WindowsConstants.au3> #include "TCP.au3" OnAutoItExitRegister("_OnExit") Func _OnExit() TCPShutdown() Exit EndFunc ;==>_OnExit #Region Global $hGUI = GUICreate("TCP AutoIT Client", 620, 400, -1, -1, -1, BitOR($WS_EX_ACCEPTFILES, $WS_EX_TOPMOST, $WS_EX_WINDOWEDGE)) Global $sMode = GUICtrlCreateRadio("Client Mode", 16, 8, 97, 17) GUICtrlSetState(-1, $GUI_CHECKED) Global $sConnectStatus = GUICtrlCreateLabel("", 408, 8, 89, 17) Global $sServerIP = GUICtrlCreateInput(@IPAddress1, 224, 8, 120, 21) Global $sServerPORT = GUICtrlCreateInput("8888", 345, 8, 39, 21) GUICtrlCreateLabel("IP Server:", 160, 10, 51, 17) Global $bStartConnect = GUICtrlCreateButton("Start Connect", 512, 6, 89, 33) Global $gMessenger = GUICtrlCreateGroup("Text to Send", 8, 64, 601, 129) Global $tMessenger = GUICtrlCreateEdit("", 15, 85, 489, 97, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "[START]kYtkjq1VuPTdNQtNlLuzUcEA56F4AaxlrhPZ3FSMd9Svss6Fflt0au6GMqMukNudNX02q7VqFVqJaaD0m5GG7hkGhg6TvblZDCZJ2YZNS1lj4t0hSmBly0nMBQYPDc3XTCUD3o4hZnROywXgaw713XHEeiuiXvu6UVXkVvlSdSlox8OkgEu0pk9zKYQJM0nfiiEaCbo4Rp6qKdDsVCtuDgQSmgsXbI5ZIV2kq59AGkX52Zy6OvH2gRuMZeW3ub0aFr9r2c2XpcNOc1FPWcMfHsk77fk8GkYrtLTAYhFt2kzKLS0KKUiVaymVXMcgGhIpeAGfGLt9RSnfgBFMxUzLWMr031ts48toWug85ktsJmdfN9uqHUNGkIEY2pOFNN88PuAq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ex9Z3xZ0e2XZQJLxKRIRq1AsZOe7s5HuIrbCNZIxzevnTPSMlhMilYrYbmQ3AmybdT20k0l99ELTVoU6tQeliov8LxEwpIgykKNSacSGBwayT0gH0EZpASsrs3rsv29NEOJzXtz94OgLiQU5BiZ5VyVl4MI4IPKyPvlog4LVgFV2qZSty9x9VXfeWTm8zxKOaBR1RV8Hi1sRw1peADLASmvCi9lQWWUw8fFFCAe5dUMhmrWGM8gGP919gKnqylw9GAl07pko9w1R6G3S1vKbvdjD9gSNXLQVf4M1G1CrfuHplDBZFGmfMrFA6uqZGptSZS2Kb4WZFCvkbcHgdDUlp2L05Oo7UhEJKhUs7hd[END]") Global $bSendMes = GUICtrlCreateButton("SEND", 511, 83, 89, 105) GUICtrlCreateGroup("", -99, -99, 1, 1) GUICtrlCreateLabel("File To Send:", 16, 200, 80, 17) Global $sPathFileSend = GUICtrlCreateInput(@TempDir & "\XXX.jpg", 104, 200, 361, 21) Global $bSelectFile = GUICtrlCreateButton(".!.", 472, 200, 35, 25) GUICtrlCreateLabel("Path To Save:", 16, 230, 80, 17) Global $sPathFileSave = GUICtrlCreateInput(@DesktopDir, 104, 230, 361, 21) Global $bSelectDir = GUICtrlCreateButton("...", 472, 230, 35, 25) Global $bSendFile = GUICtrlCreateButton("Send File", 512, 195, 89, 60) ;~ Global $tStatus = GUICtrlCreateLabel("", 16, 45, 580, 17) Global $gReceived = GUICtrlCreateGroup("Received", 8, 266, 601, 129) Global $cDataReceived = GUICtrlCreateEdit("", 16, 282, 585, 105, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "") GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) #EndRegion Global $hClient, $xSocket, $xServerIP, $xServerPORT, $xPathFileSend, $xPathFileSave While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $bStartConnect $xServerIP = GUICtrlRead($sServerIP) $xServerPORT = GUICtrlRead($sServerPORT) _WriteLog("Server Port: " & $xServerIP) _WriteLog("Server Port: " & $xServerPORT) $hClient = _TCP_Client_Create($xServerIP, $xServerPORT) ; Create the client. Which will connect to the local ip address on port xxxx _TCP_RegisterEvent($hClient, $TCP_RECEIVE, "Received") ; Function "Received" will get called when something is received _TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected") ; And func "Connected" will get called when the client is connected. _TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "Disconnected") ; And "Disconnected" will get called when the server disconnects us, or when the connection is lost. _WriteLog("CLIENT: Connecting...") Case $bSendFile ConsoleWrite("Send File Pressed!" & @CRLF) ;~ Exit Case $bSendMes $xMessenger = GUICtrlRead($tMessenger) _TCP_Send($xSocket, $xMessenger) ConsoleWrite("Send Messenger Pressed!" & @CRLF) Case $bSelectFile $xPathFileSend = FileOpenDialog("Select file to send:", @DesktopDir, "All (*.*)", 3, "", $hGUI) If Not @error Then GUICtrlSetData($sPathFileSend, $xPathFileSend) Case $bSelectDir $xPathFileSave = FileSelectFolder("Select local to save file received:", @DesktopDir, 0, @ScriptDir, $hGUI) If Not @error Then GUICtrlSetData($sPathFileSave, $xPathFileSave) EndSwitch Sleep(1) WEnd Func Connected($hSocket, $iError) If Not $iError Then _WriteLog("CLIENT: Connected!") GUICtrlSetData($bStartConnect, "Conneced") GUICtrlSetState($bStartConnect, $GUI_DISABLE) _WriteLog( "CLIENT: Conneced") ;~ _TCP_Send($hSocket, "Conneced :)") ;~ $xMessenger = GUICtrlRead($tMessenger) ;~ _TCP_Send($hSocket, $xMessenger) ;~ _WriteLog("CLIENT: Try reply socket: " & $hSocket & " data: " & $xMessenger) Else _WriteLog("CLIENT: Could not connect. Are you sure the server is running?") EndIf EndFunc ;==>Connected Func Received($hSocket, $sReceived, $iError) _WriteLog("CLIENT: We received from socket: " & $hSocket & " data: " & $sReceived) Sleep(1000) EndFunc ;==>Received Func Disconnect($hSocket, $iError) _WriteLog("SERVER: Client disconnected. Socket:" & $hSocket) EndFunc ;==>Disconnect Func _WriteLog($sLogMsg) Local $OldLog = GUICtrlRead($cDataReceived) GUICtrlSetData($cDataReceived, $OldLog & @CRLF & $sLogMsg) ;~ GUICtrlSetData($tStatus, $sLogMsg) ConsoleWrite("! " & $sLogMsg & @CRLF) $iEnd = StringLen(GUICtrlRead($tMessenger)) _GUICtrlEdit_SetSel($tMessenger, $iEnd, $iEnd) _GUICtrlEdit_Scroll($tMessenger, $SB_SCROLLCARET) $iEnd = StringLen(GUICtrlRead($cDataReceived)) _GUICtrlEdit_SetSel($cDataReceived, $iEnd, $iEnd) _GUICtrlEdit_Scroll($cDataReceived, $SB_SCROLLCARET) EndFunc ;==>_WriteLog Func GetIP($i = "ip") Local $return, $IP = StringSplit(BinaryToString(InetRead("http://api.wipmania.com/")), "<br>", 1) If $i = "from" Then If Not $IP[1] = "" Then $return = $IP[2] Else Return "Error: Api not responding." EndIf Else If Not $IP[1] = "" Then $return = $IP[1] Else Return "Error: Api not responding." EndIf EndIf Return $return EndFunc ;==>GetIP TCP.au3
      #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.0.0 Author: Kip Script Function: TCP UDF v3 #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #cs Functions: _TCP_Server_Create($iPort, $sIP="0.0.0.0") _TCP_Server_Broadcast($sData) _TCP_Server_ClientList() _TCP_Server_ClientIP($hSocket) _TCP_Server_DisconnectClient($hSocket) _TCP_Server_Stop() _TCP_Client_Create($sIP , $iPort) _TCP_Client_Stop($hSocket) _TCP_Send($hSocket, $sText) _TCP_RegisterEvent($hSocket, $iEvent, $sFunction) Register event values: $TCP_SEND ; Function ($hSocket, $iError) $TCP_RECEIVE ; Function ($hSocket, $sReceived, $iError) $TCP_CONNECT ; Function ($hSocket, $iError) => Client only $TCP_DISCONNECT ; Function ($hSocket, $iError) $TCP_NEWCLIENT ; Function ($hSocket, $iError) => Server only #ce Global Const $FD_READ = 1 Global Const $FD_WRITE = 2 Global Const $FD_OOB = 4 Global Const $FD_ACCEPT = 8 Global Const $FD_CONNECT = 16 Global Const $FD_CLOSE = 32 Global $hWs2_32 = -1 Global Const $TCP_SEND = 1 Global Const $TCP_RECEIVE = 2 Global Const $TCP_CONNECT = 4 Global Const $TCP_DISCONNECT = 8 Global Const $TCP_NEWCLIENT = 16 TCPStartup() Global Const $__TCP_WINDOW = GUICreate("Async Sockets UDF") Global $__TCP_SOCKETS[1][7] ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_Create ; Description ...: Initializes the server. ; Syntax.........: _TCP_Server_Create($iPort, $sIP="0.0.0.0") ; Parameters ....: $iPort - The port number the server should listen to. ; $sIP - IP address. (Default = "0.0.0.0") ; Return values .: The socket handle. ; Author ........: Kip ; Modified.......: ; Remarks .......: Only 1 server can be created per script. ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_Create($iPort, $sIP="0.0.0.0") Local $hListenSocket = ___ASocket() ___ASockSelect( $hListenSocket, $__TCP_WINDOW, 0x0400, $FD_ACCEPT) GUIRegisterMsg( 0x0400, "___TCP_OnAccept" ) ___ASockListen( $hListenSocket, $sIP, $iPort ) $__TCP_SOCKETS[0][0] = $hListenSocket $__TCP_SOCKETS[0][1] = 0x0400 Return $hListenSocket EndFunc Func ___TCP_OnAccept($hWnd, $iMsgID, $WParam, $LParam) Local $hSocket = $WParam Local $iError = ___HiWord( $LParam ) Local $iEvent = ___LoWord( $LParam ) Local $hClient, $uBound Abs($hWnd) ; Stupid AU3Check... If $iMsgID = $__TCP_SOCKETS[0][1] Then If $iEvent = $FD_ACCEPT Then If Not $iError Then ReDim $__TCP_SOCKETS[UBound($__TCP_SOCKETS)+1][7] $uBound = UBound($__TCP_SOCKETS) $hClient = TCPAccept($hSocket) ___ASockSelect($hClient, $__TCP_WINDOW, 0x0400 + $uBound - 1, BitOR($FD_READ, $FD_WRITE, $FD_CLOSE)) GUIRegisterMsg(0x0400 + $uBound - 1, "___TCP_Server_OnSocketEvent" ) $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][0] = $hClient $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][1] = 0x0400 + $uBound - 1 Call($__TCP_SOCKETS[0][6], $hClient, $iError) Else Call($__TCP_SOCKETS[0][6], 0, $iError) EndIf ElseIf $iEvent = $FD_CONNECT Then Call($__TCP_SOCKETS[0][4], $hSocket, $iError) EndIf EndIf EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Client_Stop ; Description ...: Stops the client. ; Syntax.........: _TCP_Client_Stop($hSocket) ; Parameters ....: $hSocket - Client socket. ; Return values .: Success - True ; Failure - False ; Author ........: Kip ; Modified.......: ; Remarks .......: The client socket is the return value of _TCP_Client_Create(). ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Client_Stop($hSocket) Local $iElement, $i $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] = $hSocket Then $iElement = $i ExitLoop EndIf Next If $iElement Then ___ASockShutdown($__TCP_SOCKETS[$iElement][0]) TCPCloseSocket($__TCP_SOCKETS[$iElement][0]) ___ArrayDelete($__TCP_SOCKETS, $iElement) Return True EndIf Return False EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_Stop ; Description ...: Stops the server, and closes all client connections. ; Syntax.........: _TCP_Server_Stop() ; Parameters ....: ; Return values .: True ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_Stop() Local $i ___ASockShutdown($__TCP_SOCKETS[0][0]) TCPCloseSocket($__TCP_SOCKETS[0][0]) $__TCP_SOCKETS[0][0] = "" $__TCP_SOCKETS[0][1] = "" $__TCP_SOCKETS[0][2] = "" $__TCP_SOCKETS[0][3] = "" $__TCP_SOCKETS[0][4] = "" $__TCP_SOCKETS[0][5] = "" $__TCP_SOCKETS[0][6] = "" For $i = UBound($__TCP_SOCKETS)-1 to 1 Step -1 ___ArrayDelete($__TCP_SOCKETS, $i) Next Return True EndFunc Func ___TCP_Server_OnSocketEvent( $hWnd, $iMsgID, $WParam, $LParam ) Local $hSocket = $WParam Local $iError = ___HiWord( $LParam ) Local $iEvent = ___LoWord( $LParam ) Local $sDataBuff, $iElement, $i Abs($hWnd) $hSocket = 0 $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][1] = $iMsgID Then $hSocket = $__TCP_SOCKETS[$i][0] $iElement = $i ExitLoop EndIf Next If $hSocket Then Switch $iEvent Case $FD_READ $sDataBuff = TCPRecv($hSocket, 1024) Call($__TCP_SOCKETS[0][2], $hSocket, $sDataBuff, $iError) Case $FD_WRITE Call($__TCP_SOCKETS[0][3], $hSocket, $iError) Case $FD_CLOSE ___ASockShutdown($hSocket) TCPCloseSocket($hSocket) Call($__TCP_SOCKETS[0][5], $hSocket, $iError) ___ArrayDelete($__TCP_SOCKETS, $iElement) EndSwitch EndIf EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_DisconnectClient ; Description ...: Disconnects a client of the server. ; Syntax.........: _TCP_Server_DisconnectClient($hSocket) ; Parameters ....: $hSocket - Client socket. ; Return values .: Success - True ; Failure - False ; Author ........: Kip ; Modified.......: ; Remarks .......: The client socket is the $hSocket parameter of a _TCP_RegisterEvent callback function. ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_DisconnectClient($hSocket) Local $iElement, $i $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] = $hSocket Then $iElement = $i ExitLoop EndIf Next If $iElement Then ___ASockShutdown($hSocket) TCPCloseSocket($hSocket) ___ArrayDelete($__TCP_SOCKETS, $iElement) Return True EndIf Return False EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_ClientList ; Description ...: Returns the sockets of all connected clients. ; Syntax.........: _TCP_Server_ClientList() ; Parameters ....: ; Return values .: An 1 dimensional array of all connected clients. ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_ClientList() Local $aReturn[1], $i For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] Then ReDim $aReturn[UBound($aReturn)+1] $aReturn[UBound($aReturn)-1] = $__TCP_SOCKETS[$i][0] EndIf Next $aReturn[0] = UBound($aReturn)-1 Return $aReturn EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_Broadcast ; Description ...: Sends data to all connected clients. ; Syntax.........: _TCP_Server_Broadcast($sData) ; Parameters ....: $sData - The data to send. ; Return values .: True ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_Broadcast($sData) Local $i For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] Then TCPSend($__TCP_SOCKETS[$i][0], $sData) Next Return True EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Client_Create ; Description ...: Creates a new client. ; Syntax.........: _TCP_Client_Create($sIP , $iPort) ; Parameters ....: $sIP - The IP address to connect to. ; $iPort - Port on which the created socket will be connected. ; Return values .: Client socket handle. ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Client_Create($sIP , $iPort) ReDim $__TCP_SOCKETS[UBound($__TCP_SOCKETS)+1][7] local $hSocket = ___ASocket() $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][0] = $hSocket $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][1] = 0x0400 + (UBound($__TCP_SOCKETS)-1) ___ASockSelect( $hSocket, $__TCP_WINDOW, 0x0400 + (UBound($__TCP_SOCKETS)-1), BitOR( $FD_READ, $FD_WRITE, $FD_CONNECT, $FD_CLOSE ) ) GUIRegisterMsg( 0x0400 + (UBound($__TCP_SOCKETS)-1), "___TCP_Client_OnSocketEvent" ) ___ASockConnect( $hSocket, $sIP, $iPort ) Return $hSocket EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_RegisterEvent ; Description ...: Registers an event. ; Syntax.........: _TCP_RegisterEvent($hSocket, $iEvent, $sFunction) ; Parameters ....: $hSocket - Socket of the server or a client. ; $iEvent - Event number. It can be any these values: ; * $TCP_SEND ; * $TCP_RECEIVE ; * $TCP_CONNECT => Client only ; * $TCP_DISCONNECT ; * $TCP_NEWCLIENT => Server only ; Return values .: Success - True ; Failure - False ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_RegisterEvent($hSocket, $iEvent, $sFunction) Local $iSelected = 0 Local $i If $__TCP_SOCKETS[0][0] Then $iSelected = 0 Else For $i = 0 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] = $hSocket Then $iSelected = $i ExitLoop EndIf Next If Not $iSelected Then Return 0 EndIf Switch $iEvent Case $TCP_SEND $__TCP_SOCKETS[$iSelected][3] = $sFunction Case $TCP_RECEIVE $__TCP_SOCKETS[$iSelected][2] = $sFunction Case $TCP_CONNECT $__TCP_SOCKETS[$iSelected][4] = $sFunction Case $TCP_DISCONNECT $__TCP_SOCKETS[$iSelected][5] = $sFunction Case $TCP_NEWCLIENT $__TCP_SOCKETS[$iSelected][6] = $sFunction Case Else Return False EndSwitch Return True EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_ClientIP ; Description ...: Converts a client socket handle to IP address. ; Syntax.........: _TCP_Server_ClientIP($hSocket) ; Parameters ....: $hSocket - Client socket handle. ; Return values .: A string with the IP address. ; Author ........: Unknown ; Modified.......: Kip ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_ClientIP($hSocket) Local $pSocketAddress, $aReturn $pSocketAddress = DllStructCreate("short;ushort;uint;char[8]") $aReturn = DllCall("Ws2_32.dll", "int", "getpeername", "int", $hSocket, "ptr", DllStructGetPtr($pSocketAddress), "int*", DllStructGetSize($pSocketAddress)) If @error Or $aReturn[0] <> 0 Then Return 0 $aReturn = DllCall("Ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($pSocketAddress, 3)) If @error Then Return 0 $pSocketAddress = 0 Return $aReturn[0] EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Send ; Description ...: Sends data to a server or client. ; Syntax.........: _TCP_Send($hSocket, $sText) ; Parameters ....: $hSocket - Client or server socket handle. ; $sText - Data to send. ; Return values .: ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Send($hSocket, $sText) Return TCPSend($hSocket, $sText) EndFunc Func ___TCP_Client_OnSocketEvent( $hWnd, $iMsgID, $WParam, $LParam ) Local $iError = ___HiWord( $LParam ) Local $iEvent = ___LoWord( $LParam ) Local $hSocket, $iElement, $i, $sDataBuff Abs($hWnd) Abs($WParam) $hSocket = 0 $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][1] = $iMsgID Then $hSocket = $__TCP_SOCKETS[$i][0] $iElement = $i ExitLoop EndIf Next If $hSocket Then Switch $iEvent Case $FD_READ; Data has arrived! $sDataBuff = TCPRecv( $hSocket, 1024) Call($__TCP_SOCKETS[$i][2], $hSocket, $sDataBuff, $iError) $sDataBuff = "" Case $FD_WRITE Call($__TCP_SOCKETS[$i][3], $hSocket, $iError) Case $FD_CONNECT Call($__TCP_SOCKETS[$i][4], $hSocket, $iError) Case $FD_CLOSE ___ASockShutdown( $hSocket ) TCPCloseSocket( $hSocket ) Call($__TCP_SOCKETS[$i][5], $hSocket, $iError) ___ArrayDelete($__TCP_SOCKETS, $iElement) EndSwitch EndIf EndFunc ;================================================================================================================== ; ; Zatorg's Asynchronous Sockets UDF Starts from here. ; ;================================================================================================================== Func ___ASocket($iAddressFamily = 2, $iType = 1, $iProtocol = 6) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $hSocket = DllCall($hWs2_32, "uint", "socket", "int", $iAddressFamily, "int", $iType, "int", $iProtocol) If @error Then SetError(1, @error) Return -1 EndIf If $hSocket[ 0 ] = -1 Then SetError(2, ___WSAGetLastError()) Return -1 EndIf Return $hSocket[ 0 ] EndFunc ;==>_ASocket Func ___ASockShutdown($hSocket) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall($hWs2_32, "int", "shutdown", "uint", $hSocket, "int", 2) If @error Then SetError(1, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then SetError(2, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockShutdown Func ___ASockClose($hSocket) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall($hWs2_32, "int", "closesocket", "uint", $hSocket) If @error Then SetError(1, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then SetError(2, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockClose Func ___ASockSelect($hSocket, $hWnd, $uiMsg, $iEvent) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall( _ $hWs2_32, _ "int", "WSAAsyncSelect", _ "uint", $hSocket, _ "hwnd", $hWnd, _ "uint", $uiMsg, _ "int", $iEvent _ ) If @error Then SetError(1, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then SetError(2, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockSelect ; Note: you can see that $iMaxPending is set to 5 by default. ; IT DOES NOT MEAN THAT DEFAULT = 5 PENDING CONNECTIONS ; 5 == SOMAXCONN, so don't worry be happy Func ___ASockListen($hSocket, $sIP, $uiPort, $iMaxPending = 5); 5 == SOMAXCONN => No need to change it. Local $iRet Local $stAddress If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) $stAddress = ___SockAddr($sIP, $uiPort) If @error Then SetError(@error, @extended) Return False EndIf $iRet = DllCall($hWs2_32, "int", "bind", "uint", $hSocket, "ptr", DllStructGetPtr($stAddress), "int", DllStructGetSize($stAddress)) If @error Then SetError(3, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then $stAddress = 0; Deallocate SetError(4, ___WSAGetLastError()) Return False EndIf $iRet = DllCall($hWs2_32, "int", "listen", "uint", $hSocket, "int", $iMaxPending) If @error Then SetError(5, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then $stAddress = 0; Deallocate SetError(6, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockListen Func ___ASockConnect($hSocket, $sIP, $uiPort) Local $iRet Local $stAddress If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) $stAddress = ___SockAddr($sIP, $uiPort) If @error Then SetError(@error, @extended) Return False EndIf $iRet = DllCall($hWs2_32, "int", "connect", "uint", $hSocket, "ptr", DllStructGetPtr($stAddress), "int", DllStructGetSize($stAddress)) If @error Then SetError(3, @error) Return False EndIf $iRet = ___WSAGetLastError() If $iRet = 10035 Then; WSAEWOULDBLOCK Return True; Asynchronous connect attempt has been started. EndIf SetExtended(1); Connected immediately Return True EndFunc ;==>_ASockConnect ; A wrapper function to ease all the pain in creating and filling the sockaddr struct Func ___SockAddr($sIP, $iPort, $iAddressFamily = 2) Local $iRet Local $stAddress If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) $stAddress = DllStructCreate("short; ushort; uint; char[8]") If @error Then SetError(1, @error) Return False EndIf DllStructSetData($stAddress, 1, $iAddressFamily) $iRet = DllCall($hWs2_32, "ushort", "htons", "ushort", $iPort) DllStructSetData($stAddress, 2, $iRet[ 0 ]) $iRet = DllCall($hWs2_32, "uint", "inet_addr", "str", $sIP) If $iRet[ 0 ] = 0xffffffff Then; INADDR_NONE $stAddress = 0; Deallocate SetError(2, ___WSAGetLastError()) Return False EndIf DllStructSetData($stAddress, 3, $iRet[ 0 ]) Return $stAddress EndFunc ;==>__SockAddr Func ___WSAGetLastError() If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall($hWs2_32, "int", "WSAGetLastError") If @error Then ;ConsoleWrite("+> _WSAGetLastError(): WSAGetLastError() failed. Script line number: " & @ScriptLineNumber & @CRLF) SetExtended(1) Return 0 EndIf Return $iRet[ 0 ] EndFunc ;==>_WSAGetLastError ; Got these here: ; http://www.autoitscript.com/forum/index.php?showtopic=5620&hl=MAKELONG Func ___MakeLong($LoWord, $HiWord) Return BitOR($HiWord * 0x10000, BitAND($LoWord, 0xFFFF)); Thanks Larry EndFunc ;==>_MakeLong Func ___HiWord($Long) Return BitShift($Long, 16); Thanks Valik EndFunc ;==>_HiWord Func ___LoWord($Long) Return BitAND($Long, 0xFFFF); Thanks Valik EndFunc ;==>_LoWord ; ========================================= Array functions ; #FUNCTION# ==================================================================================================================== ; Name...........: _ArrayDelete ; Description ...: Deletes the specified element from the given array. ; Syntax.........: _ArrayDelete(ByRef $avArray, $iElement) ; Parameters ....: $avArray - Array to modify ; $iElement - Element to delete ; Return values .: Success - New size of the array ; Failure - 0, sets @error to: ; |1 - $avArray is not an array ; |3 - $avArray has too many dimensions (only up to 2D supported) ; |(2 - Deprecated error code) ; Author ........: Cephas <cephas at clergy dot net> ; Modified.......: Jos van der Zande <jdeb at autoitscript dot com> - array passed ByRef, Ultima - 2D arrays supported, reworked function (no longer needs temporary array; faster when deleting from end) ; Remarks .......: If the array has one element left (or one row for 2D arrays), it will be set to "" after _ArrayDelete() is used on it. ; Related .......: _ArrayAdd, _ArrayInsert, _ArrayPop, _ArrayPush ; Link ..........; ; Example .......; Yes ; =============================================================================================================================== Func ___ArrayDelete(ByRef $avArray, $iElement) If Not IsArray($avArray) Then Return SetError(1, 0, 0) Local $iUBound = UBound($avArray, 1) - 1 If Not $iUBound Then $avArray = "" Return 0 EndIf ; Bounds checking If $iElement < 0 Then $iElement = 0 If $iElement > $iUBound Then $iElement = $iUBound ; Move items after $iElement up by 1 Switch UBound($avArray, 0) Case 1 For $i = $iElement To $iUBound - 1 $avArray[$i] = $avArray[$i + 1] Next ReDim $avArray[$iUBound] Case 2 Local $iSubMax = UBound($avArray, 2) - 1 For $i = $iElement To $iUBound - 1 For $j = 0 To $iSubMax $avArray[$i][$j] = $avArray[$i + 1][$j] Next Next ReDim $avArray[$iUBound][$iSubMax + 1] Case Else Return SetError(3, 0, 0) EndSwitch Return $iUBound EndFunc ;==>_ArrayDelete  
      Problem:
      - Can not send and receive between Client and Server!
      - Data loss, data reception is not complete.
    • ripdad
      By ripdad
      Reproducer...
      TCPStartup() ; TCPConnect('212.227.91.231', '80') Local $error = @error MsgBox(0, 'AutoIt Version: ' & @AutoItVersion, 'AutoIt Error: ' & $error & @CRLF & 'WSAError: ' & _WSAGetLastErrorEx() & @TAB) TCPShutDown() ; Func _WSAGetLastErrorEx() Local $a = DllCall('ws2_32.dll', 'int', 'WSAGetLastError') If @error Or Not IsArray($a) Then Return SetError(1, 0, 'FuncError -1') $a = DllCall('kernel32.dll', 'int', 'FormatMessage', 'int', 0x00001000, 'ptr', 0, 'int', $a[0], 'int', 0, 'str', 0, 'int', 2048, 'ptr', 0) If @error Or Not IsArray($a) Then Return SetError(1, 0, 'FuncError -2') Return $a[3] & ' - ' & StringStripWS($a[5], 7) EndFunc Tested: autoit-v3.3.12.0, autoit-v3.3.14.0 and autoit-v3.3.15.0 beta on Win7.
      Seems to have started with autoit-v3.3.14.0.