TCPClient

This UDF contains function for simply handling a TCP Client.

Example

This script is an example of using this UDF, it’s a very basic TCP Chat client.  You can use it with the TCP Server example.

;----------------------------------------------------------------------------
;
; AutoIt Version: 3.3.6.1
; Author:         Matwachich
;
; Script Function:
;
;
;----------------------------------------------------------------------------
#NoTrayIcon

#include <GuiEdit.au3>
#include "TCPClient.au3"

TCPStartup()

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

; On demande un nom d'utilisateur
; Wee need a user name
Do
    $__NickName = InputBox("Chat", "Entrez votre pseudo")
    If @error Then Exit
Until $__NickName

#Region ### START Koda GUI section ### Form=
$GUI = GUICreate("Chat", 378, 256, 384, 171)
$Edit = GUICtrlCreateEdit("", 6, 6, 365, 215, BitOR($ES_AUTOVSCROLL,$ES_READONLY,$ES_WANTRETURN,$WS_VSCROLL))
$Input = GUICtrlCreateInput("", 6, 228, 283, 21)
$Button1 = GUICtrlCreateButton("Envoyer", 294, 228, 75, 21)
Global $accels[1][2] = [["{enter}", $Button1]]
GuiSetAccelerators($accels)
$accels = 0
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

Global $tmp, $connTimer = TimerInit()

; On créer un client et on lui assigne des fonction callback
; Client creation, and callbacks functions assigning
Global $Client = _TCPClient_Create(@IPAddress1, 53698, "motdepassedecryptagedesdonneessupersecret")
_TCPClient_SetCallbacks($Client, "_TCP_Recv")

; Boucle principale
; Main loop
While 1
    Switch GUIGetMsg()
        ; Avant de quitter, on detruit le client
        ; Befor exit, we destroy the client
        Case $GUI_EVENT_CLOSE
            _TCPClient_Destroy($Client)
            TCPShutdown()
            Exit
        ; ---
        ; Envoi d'un message, seulement si le Input contient quelque chose
        ; Sending message, only if there is something in the Input
        Case $Button1
            $tmp = GuiCtrlRead($Input)
            If $tmp Then
                _TCPClient_Send($Client, $tmp)
                GuiCtrlSetData($Input, "")
            EndIf
        ; ---
    EndSwitch
    ; ---
    ; Si le client est déconnecté, on essay de se connecter 1 fois / seconde
    ; If the client is disconnected, then we indefinitly try to connect once per second
    If Not _TCPClient_IsConnected($Client) Then
        If TimerDiff($connTimer) >= 1000 Then
            _TCPClient_Connect($Client)
            $connTimer = TimerInit()
        EndIf
    EndIf
    ; ---
    ; Fonction de traitement
    ; Processing function
    _TCPClient_Process()
WEnd

; Fonction appelée à la reception d'un message depuis le serveur
; Function called when a message is received from the server
Func _TCP_Recv($iClient, $Data)
    ; Cette ligne ne sert à rien puisque nous n'avons qu'un seul client dans le script, mais si nous
    ; en avion plusieurs, elle permetterai si tous les clients avait la même fonction callback de réception,
    ; de savoir de quel client émane le message reçu
    ; This line isn't very usefull in our example, but it would be usefull in a script containing many clients
    ; in order to (if all the client had the same callback function) know which client is concerned by the event
    If $iClient <> $Client Then Return
    ; ---
    ; Si le message reçu est une requète d'identification, alors on s'identify au pres du serveur
    ; If the message received is an identification request, then we identify ourself to the server
    If $Data = "#IDENTIFY#" Then
        _TCPClient_Send($iClient, "#NAME#" & $__NickName)
        Return
    EndIf
    ; ---
    ; Si non, ça veut dir que c'est un simple message, alors on l'affiche de le Edit
    ; Else, it's a simple chat message, so we display it in the Edit
    Local $read = GuiCtrlRead($Edit)
    GuiCtrlSetData($Edit, $read & $Data & @CRLF)
    _GUICtrlEdit_LineScroll($Edit, 0, _GUICtrlEdit_GetLineCount($Edit))
EndFunc
Summary
TCPClientThis UDF contains function for simply handling a TCP Client.
Creation/Destruction, Connect/Disconnect
Functions
_TCPClient_CreateCreate a TCP Client
_TCPClient_DestroyDestroy a client
_TCPClient_ConnectOrder a Client to connect
_TCPClient_DisconnectOrder a client to disconnect
_TCPClient_IsConnectedCheck if a client is connected
Configuration
Functions
_TCPClient_ConfigSet client’s configuration
_TCPClient_SetCallbacksSet the callback functions that will be called when an event occurs
Communication with server
Functions
_TCPClient_SendSend data to the server
Processing
Functions
_TCPClient_ProcessThis function makes all clients work, all data is processed here, and all callbacks are called from here

Creation/Destruction, Connect/Disconnect

Summary
Functions
_TCPClient_CreateCreate a TCP Client
_TCPClient_DestroyDestroy a client
_TCPClient_ConnectOrder a Client to connect
_TCPClient_DisconnectOrder a client to disconnect
_TCPClient_IsConnectedCheck if a client is connected

Functions

_TCPClient_Create

Create a TCP Client

Syntax

_TCPClient_Create($sIP, $iPort, $sCryPwd = "", $iTimeOut = 60)

Parameters

$sIPServer’s IP Address
$iPortServer’s listening port
$sCryPwdIf specified, then the exchanged data between server and clients will be encrypted (must be the same as the client)
$iCompressLvlZLib compression level, 0 - No compression, 9 - Max compression
$iTimeOutServer Time-out (seconds)

Return

SuccesA Client Handle
Failed0 and set @error to 1 if maximum clients number is already reached, in this case, you must destroy some other client to create a new one (see _TCPClient_Destroy).

_TCPClient_Destroy

Destroy a client

Syntax

_TCPClient_Destroy($iClient)

Parameters

$iClientClient Handle (Returned by _TCPClient_Create)

Return

Sucess1
Failed0 and set @error to -1 if the Client Handle isn’t valid

Remark

If the client was connect, then the _TCPClient_Disconnect function is called befor destroying the client.  Consequently, the Lost Connexion Callback function will be called for this client.

_TCPClient_Connect

Order a Client to connect

Syntax

_TCPClient_Connect($iClient)

Parameters

$iClientClient Handle (Returned by _TCPClient_Create)

Return

Succes1
Failed0 (Check Server IP, and Port)

_TCPClient_Disconnect

Order a client to disconnect

Syntax

_TCPClient_Disconnect($iClient)

Parameters

$iClientClient Handle (Returned by _TCPClient_Create)

Return

Sucess1
Failed0 and set @error to
  • -1 if the Client Handle isn’t valid
  • 1 if the client isn’t connected to any server

_TCPClient_IsConnected

Check if a client is connected

Syntax

_TCPClient_IsConnected($iClient)

Parameters

$iClientClient Handle (Returned by _TCPClient_Create)

Return

Succes1 if the client is connected, 0 if it isn’t connect
Failed0 and set @error to -1 if the Client Handle isn’t valid

Configuration

Summary
Functions
_TCPClient_ConfigSet client’s configuration
_TCPClient_SetCallbacksSet the callback functions that will be called when an event occurs

Functions

_TCPClient_Config

Set client’s configuration

Syntax

_TCPClient_Config($iClient, $sIP = Default, $iPort = Default, $iTimeOut = Default)

Parameters

$iClientClient Handle (Returned by Creation/Destruction, Connect/Disconnect._TCPClient_Create)
$sIPServer’s IP Address
$iPortServer’s listening port
$iTimeOutServer Time-out (seconds)

Returns

Succes1
Failed0 and set @error to -1 if the Client Handle isn’t valid

_TCPClient_SetCallbacks

Set the callback functions that will be called when an event occurs

Syntax

_TCPClient_SetCallbacks($iClient, $sCB_Recv = Default, $sCB_Receiving = Default, $sCB_LostConnection = Default, $sCB_TimedOut = Default)

Parameters

$iClientClient Handle (Returned by Creation/Destruction, Connect/Disconnect._TCPClient_Create)
$sCB_RecvFunction called when data is received from the server
$sCB_ReceivingFunction called when being receiving data from the server
$sCB_LostConnectionFunction called when disconnecting from the server
$sCB_TimedOutFunction called when the server is timed out

Returns

Succes1
Failed0 and set @error to -1 if the Client Handle isn’t valid

Remark

The syntax for each callback function is:

  • $sCB_Recv _Function($iClient, $Data)
  • $sCB_Receiving & sCB_TimedOut _Function($iClient, $iBufferLenght)
  • $sCB_LostConnection _Function($iClient)
$iClientClient Handle concerned by the event
$DataData received, either String or Binary (is it was sent)
$iBufferLenghtLenght of the buffer at the moment whet the function is called

When the server is timed out, the buffer will be flushed, so $iBufferLenght corresponds to the amount of lost data.

Communication with server

Summary
Functions
_TCPClient_SendSend data to the server

Functions

_TCPClient_Send

Send data to the server

Syntax

_TCPClient_Send($iClient, $Data)

Parameters

$iClientClient Handle (Returned by Creation/Destruction, Connect/Disconnect._TCPClient_Create)
$DataData we want to send (See remark)

Returns

SuccesReturns number of bytes sent.
Failed0 and set @error to

Remark

About $Data parameter, anything other than Binary data will be sent as string, and received as a string.  Binary data will be sent as it is, and received as binary too.

Processing

Summary
Functions
_TCPClient_ProcessThis function makes all clients work, all data is processed here, and all callbacks are called from here

Functions

_TCPClient_Process

This function makes all clients work, all data is processed here, and all callbacks are called from here

Syntax

_TCPClient_Process()

Parameters

None

Returns

1

Destroy a client
Create a TCP Client
Order a client to disconnect
Close