TCPServer

This UDF contains function for handling a multi-clients, encrypted TCP Server.

Example

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

;----------------------------------------------------------------------------
;
; AutoIt Version: 3.3.6.1
; Author:         Matwachich
;
; Script Function:
;   TCP Chat Server example
;
;----------------------------------------------------------------------------
#NoTrayIcon

#include "TCPServer.au3"

TCPStartup()

; Créer un serveur TCP
; Create the server
_TCPServer_Create(@IPAddress1, 53698, 50, 1, "motdepassedecryptagedesdonneessupersecret")

; Lui assigner ses fonctions callback en fonction des evenements
; Assign it callback functions, that will be called when events occurs
_TCPServer_SetCallbacks("_TCP_New", "_TCP_Lost", "_TCP_Recv")

; On démare le serveur
; Start the server
If Not _TCPServer_Start() Then Exit MsgBox(16, "Erreur", "Impossible de démarer le serveur!")

; Boucle principale, où est appelée la fonction de traitement
; Main loop, where the processing function is called
Global $run = 1
While $run
    _TCPServer_Process()
Wend

; A la sortie de la boucle, on détruit le serveur
; Destroy the server and free ressources
_TCPServer_Destroy()
TCPShutdown()

; ##############################################################

; Fonction appelée lors de la connexion d'un nouveau client
; elle envoi à ce client une requète d'identification
; Function called when a new client connects
; it sends to the new connected client an identify request
Func _TCP_New($iSocket, $sIP)
    _TCPServer_Send($iSocket, "#IDENTIFY#")
    ; ---
    ConsoleWrite("New Client!" & @CRLF)
EndFunc

; Fonction appelée lors de la deconnexion d'un client
; elle envoi à tous le monde la notification de deconnexion
; Function called when a client disconnects
; it sends to other clients a disconnect notification
Func _TCP_Lost($iSocket, $sIP)
    Local $nick = _TCPServer_ClientPropertyGet($iSocket, 0)
    If $nick Then _TCPServer_Broadcast($nick & " Disconnected!")
    ; ---
    ConsoleWrite("Lost Client!" & @CRLF)
EndFunc

; Fonction appelée lors de la réception d'un message d'un client
; Function called when a message is received from a client
Func _TCP_Recv($iSocket, $sIP, $Data)
    ; Si le message est #CLOSE#:
    ;   Notifie que quelqu'un a demandé la fermeture du serveur
    ;   Et met la variable $run à 0
    ; If the message is #CLOSE#:
    ;   We notify all clients that somebody requested closing the server
    ;   We set $run to 0
    If $Data = "#CLOSE#" Then
        Local $nick = _TCPServer_ClientPropertyGet($iSocket, 0)
        If $nick Then
            _TCPServer_Broadcast($nick & " closed the server...")
            $run = 0
        EndIf
    ; ---
    ; Si le message commence par #NAME#: Ca veut dir que ce client s'identifie
    ;   On extrait son nom du message (avec le StringTrimLeft)
    ;   On l'assigne à la propriété N°0 de sa socket
    ;   On notifie de la connexion d'une nouvelle personne dans le chat
    ; If the message starts with #NAME#: It means that it's an identification
    ;   We extract the name from the received data (With StringTrimleft)
    ;   We assign it to the client's property N°0
    ;   We notify everybody that a new client is connected
    ElseIf StringLeft($Data, 6) = "#NAME#" Then
        Local $nick = StringTrimLeft($Data, 6)
        _TCPServer_ClientPropertySet($iSocket, 0, $nick)
        _TCPServer_Broadcast($nick & " Connected!")
    ; ---
    ; Si non, ça veut dir que c'est un simple message, alors on le renvoi
    ; à tous le monde, en y préfixant le nom de la personne (contenu dans la
    ; propriété N°0 de la socket)
    ; Else, it's a simple message, so we broadcast it to every body, after adding
    ; to it as a prefix, the name of the client (contained in the client's property N°0)
    Else
        Local $nick = _TCPServer_ClientPropertyGet($iSocket, 0)
        If $nick Then _TCPServer_Broadcast("[" & $nick & "] " & $Data)
    EndIf
EndFunc
Summary
TCPServerThis UDF contains function for handling a multi-clients, encrypted TCP Server.
Creation/Destruction, Start/Stop
Functions
_TCPServer_CreateCreate a TCP server
_TCPServer_StartStarts the server
_TCPServer_StopStops the server
_TCPServer_IsStartedReturn server status
_TCPServer_DestroyDestroy the server and free ressources
Configuration
Functions
_TCPServer_ConfigSet server’s parameters
_TCPServer_SetCallbacksSet the callback functions that will be called when an event occurs
Clients handling
Functions
_TCPServer_SendSend data to a client
_TCPServer_BroadcastSend data to all connected clients
_TCPServer_DisconnectDisconnect a client
_TCPServer_DisconnectAllDisconnect all clients
_TCPServer_GetBufferLenReturn the current buffer lenght of a client
_TCPServer_SocketListReturn a list off all connected Socket IDs and their respective IP addresses
_TCPServer_ClientCountReturn the number of currently connected clients
Various conversions
Functions
_TCPServer_SocketID2IPConvert Socket ID to IP Address
_TCPServer_IP2SocketIDConvert an IP Address to Socket ID
_TCPServer_SocketID2SocketHandleGet the Socket Handle of the corresponding Socket ID
_TCPServer_SocketHandle2SocketIDConvert Socket Handle to Socket ID
Client’s properties
Functions
_TCPServer_ClientPropertyGetReturn client’s property current value
_TCPServer_ClientPropertySetSet client’s propery value
Processing
Functions
_TCPServer_ProcessThis function makes the server work, all data is processed here, and all callbacks are called from here

Creation/Destruction, Start/Stop

Summary
Functions
_TCPServer_CreateCreate a TCP server
_TCPServer_StartStarts the server
_TCPServer_StopStops the server
_TCPServer_IsStartedReturn server status
_TCPServer_DestroyDestroy the server and free ressources

Functions

_TCPServer_Create

Create a TCP server

Syntax

_TCPServer_Create($sIP, $iPort, $iMaxClients = 50, $iClientPropertiesNbr = 0, $sPwd = "", $iTimeOut = 60)

Parameters

$sIPIP address to listen
$iPortPort number to listen
$iMaxClientsMax number of simultaneous connected clients
$iClientPropertiesNbrDefines the number of properies that we can assigne for each client
$sPwdIf 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
$iTimeOutClient time-out (Seconds)

Return

1

Remark

Call this function ONLY ONE TIME in a script

_TCPServer_Start

Starts the server

Syntax

_TCPServer_Start()

Parameters

None

Return

Succes1
Failed0 - Check IP (is it valid), and Port (is it free)

_TCPServer_Stop

Stops the server

Syntax

_TCPServer_Stop()

Parameters

None

Return

Succes1
Failed0

_TCPServer_IsStarted

Return server status

Syntax

Parameters

None

Return

1Server is listening (started)
0Server is shutdown

_TCPServer_Destroy

Destroy the server and free ressources

Syntax

_TCPServer_Destroy()

Parameters

None

Return

1

Configuration

Summary
Functions
_TCPServer_ConfigSet server’s parameters
_TCPServer_SetCallbacksSet the callback functions that will be called when an event occurs

Functions

_TCPServer_Config

Set server’s parameters

Syntax

_TCPServer_Config($sIP = Default, $iPort = Default, $iTimeOut = Default, $iMaxClients = Default, $iClientPropertiesNbr = Default)

Parameters

$sIP (Optional)IP address to listen
$iPort (Optional)Port to listen
$iTimeOut (Optional)Client time-out (seconds)
$iMaxClients (Optional)Max number of simultaneous connected clients
$iClientPropertiesNbr (Optional)Defines the number of properies that we can assigne for each client

Return

1

Remarks

  • Any parameter that is passed the Default keyword will not be modified
  • The new parameters are took in consideration only if the server is stoped (<_TCPServer_Stop>) and restarted (<_TCPServer_Start>)

_TCPServer_SetCallbacks

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

Syntax

_TCPServer_SetCallbacks($sCB_NewClient = Default, $sCB_LostClient = Default, $sCB_Recv = Default, $sCB_Receiving = Default, $sCB_TimedOut = Default)

Parameters

$sCB_NewClient (Optional)Function called when a client connects to the server
$sCB_LostClient (Optional)Function called when a client disconnects from the server
$sCB_Recv (Optional)Function called when some data is received from a client
$sCB_Receiving (Optional)Function called when a client is sending some data
$sCB_TimedOut (Optional)Function called when a client is timed out being sending

Return

1

Remark

The syntax for each callback function is:

  • $sCB_NewClient & $sCB_LostClient _Function($iSocket, $sIP)
  • $sCB_Recv _Function($iSocket, $sIP, $Data)
  • $sCB_Receiving & $sCB_TimedOut _Function($iSocket, $sIP, $iBufferLenght)
$iSocketThe socket ID of the client that is concerned by the event
$sIPthe IP Address of the client
$DataThe data received, either String or Binary (is it was sent)
$iBufferLenghtLenght of the buffer at the moment whet the function is called

When a client is timed out, it’s buffer will be flushed, so $iBufferLenght corresponds to the amount of lost data.

WARNING\: In Lost Client callback function, if calling <_TCPServer_SocketList> then the disconnected client’s Socket ID will be in the list!  This is due to the internal mechanisms of the Processing function.

But after the Lost Client callback function, everything will become normal, and the disconnected socket will not be in the list.

Clients handling

Summary
Functions
_TCPServer_SendSend data to a client
_TCPServer_BroadcastSend data to all connected clients
_TCPServer_DisconnectDisconnect a client
_TCPServer_DisconnectAllDisconnect all clients
_TCPServer_GetBufferLenReturn the current buffer lenght of a client
_TCPServer_SocketListReturn a list off all connected Socket IDs and their respective IP addresses
_TCPServer_ClientCountReturn the number of currently connected clients

Functions

_TCPServer_Send

Send data to a client

Syntax

_TCPServer_Send($iSocket, $Data)

Parameters

$iSocketSocket ID of the client
$DataData we want to send (See remark)

Return

SuccesReturns number of bytes sent.
Failed0 and set @error to windows API WSAGetError return value (see http://msdn.microsoft.com/en-us/library/ms740668.aspx)

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.

_TCPServer_Broadcast

Send data to all connected clients

Syntax

_TCPServer_Broadcast($Data)

Parameters

$DataData we want to send (See remark in _TCPServer_Send)

Return

1

_TCPServer_Disconnect

Disconnect a client

Syntax

_TCPServer_Disconnect($iSocket)

Parameters

$iSocketSocket ID of a client

Return

Succes1
Failed0 and set @error to windows API WSAGetError return value (see http://msdn.microsoft.com/en-us/library/ms740668.aspx)

_TCPServer_DisconnectAll

Disconnect all clients

Syntax

_TCPServer_DisconnectAll()

Parameters

None

Return

1

_TCPServer_GetBufferLen

Return the current buffer lenght of a client

Syntax

_TCServer_GetBufferLen($iSocket)

Parameters

$iSocketSocket ID

Return

SuccesCurrent buffer lenght (BinaryLen)
Failed-1 and set @error to
  • -1 if the server isn’t started
  • 1 if the Socket ID isn’t valid

_TCPServer_SocketList

Return a list off all connected Socket IDs and their respective IP addresses

Syntax

_TCPServer_SocketList()

Parameters

None

Return

Succes2-D array with: - $array[0][0] = number of elements in the list (number of connected clients)
  • $array[$i][0] = Socket ID
  • $array[$i][1] = IP Address
Failed0 and set @error to -1 if the server isn’t started

_TCPServer_ClientCount

Return the number of currently connected clients

Syntax

_TCPServer_ClientCount()

Parameters

None

Return

SuccesNumber of connected clients
Failed0 and set @error to -1 if the server isn’t started

Various conversions

Summary
Functions
_TCPServer_SocketID2IPConvert Socket ID to IP Address
_TCPServer_IP2SocketIDConvert an IP Address to Socket ID
_TCPServer_SocketID2SocketHandleGet the Socket Handle of the corresponding Socket ID
_TCPServer_SocketHandle2SocketIDConvert Socket Handle to Socket ID

Functions

_TCPServer_SocketID2IP

Convert Socket ID to IP Address

Syntax

_TCPServer_SocketID2IP($iSocket)

Parameters

$iSocketSocket ID

Return

Sucess - Failed - 0 and set @error to

  • -1 if the server isn’t started
  • 1 if the Socket ID isn’t valid

_TCPServer_IP2SocketID

Convert an IP Address to Socket ID

Syntax

_TCPServer_IP2SocketID($sIP)

Parameters

$sIPIP Address

Return

SucessSocket ID
Failed0 and set @error to
  • -1 if the server isn’t started
  • 1 if the address ip doesn’t corresponds to any Socket ID

_TCPServer_SocketID2SocketHandle

Get the Socket Handle of the corresponding Socket ID

Syntax

_TCPServer_SocketID2SocketHandle($iSocket)

Parameters

$iSocketSocket ID

Return

SucessSocket Handle, or -1 if the Socket ID isn’t currently connected (attributed to a client)
Failed0 and set @error to
  • -1 if the server isn’t started
  • 1 if the socket ID isn’t valid

Remark

A Socket ID is a number between 1 and the maximum number of clients of the server, the Socket Handle is the corresponding handle, usable by native AutoIt TCP functions, of the a Socket ID

_TCPServer_SocketHandle2SocketID

Convert Socket Handle to Socket ID

Syntax

_TCPServer_SocketHandle2SocketID($hSocket)

Parameters

$hSocketSocket Handle

Return

SucessSocketID of the client
Failed0 and set @error to

Remark

See _TCPServer_SocketID2SocketHandle

Client’s properties

Summary
Functions
_TCPServer_ClientPropertyGetReturn client’s property current value
_TCPServer_ClientPropertySetSet client’s propery value

Functions

_TCPServer_ClientPropertyGet

Return client’s property current value

Syntax

_TCPServer_ClientPropertyGet($iSocket, $iProperty)

Parameters

$iSocketSocket ID of a client
$iProperty0-based index of the property

Return

SuccesValue of the property
Failed0 and set @error to
  • -1 if the server isn’t started
  • -2 if client’s properties number is 0 (see <_TCPServer_Create>)
  • 1 if the Socket ID is invalid
  • 2 if the Property ID is invalid

_TCPServer_ClientPropertySet

Set client’s propery value

Syntax

_TCPServer_ClientPropertySet($iSocket, $iProperty, $Value)

Parameters

$iSocketSocket ID of a client
$iProperty0-based index of the property
$ValueValue to assign

Return

Succes1
Failed0 and set @error to
  • -1 if the server isn’t started
  • -2 if client’s properties number is 0 (see <_TCPServer_Create>)
  • 1 if the Socket ID is invalid
  • 2 if the Property ID is invalid

Processing

Summary
Functions
_TCPServer_ProcessThis function makes the server work, all data is processed here, and all callbacks are called from here

Functions

_TCPServer_Process

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

Syntax

_TCPServer_Process()

Parameters

None

Return

Sucess1
Failed0 and set @error to -1 if the server isn’t started

Remark

This function must be called indefinitly in your main loop or with AdLibRegister

Send data to a client
Get the Socket Handle of the corresponding Socket ID
Close