This UDF contains function for handling a multi-clients, encrypted TCP Server.
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
TCPServer | This UDF contains function for handling a multi-clients, encrypted TCP Server. |
Creation/ | |
Functions | |
_TCPServer_Create | Create a TCP server |
_TCPServer_Start | Starts the server |
_TCPServer_Stop | Stops the server |
_TCPServer_IsStarted | Return server status |
_TCPServer_Destroy | Destroy the server and free ressources |
Configuration | |
Functions | |
_TCPServer_Config | Set server’s parameters |
_TCPServer_SetCallbacks | Set the callback functions that will be called when an event occurs |
Clients handling | |
Functions | |
_TCPServer_Send | Send data to a client |
_TCPServer_Broadcast | Send data to all connected clients |
_TCPServer_Disconnect | Disconnect a client |
_TCPServer_DisconnectAll | Disconnect all clients |
_TCPServer_GetBufferLen | Return the current buffer lenght of a client |
_TCPServer_SocketList | Return a list off all connected Socket IDs and their respective IP addresses |
_TCPServer_ClientCount | Return the number of currently connected clients |
Various conversions | |
Functions | |
_TCPServer_SocketID2IP | Convert Socket ID to IP Address |
_TCPServer_IP2SocketID | Convert an IP Address to Socket ID |
_TCPServer_SocketID2SocketHandle | Get the Socket Handle of the corresponding Socket ID |
_TCPServer_SocketHandle2SocketID | Convert Socket Handle to Socket ID |
Client’s properties | |
Functions | |
_TCPServer_ClientPropertyGet | Return client’s property current value |
_TCPServer_ClientPropertySet | Set client’s propery value |
Processing | |
Functions | |
_TCPServer_Process | This function makes the server work, all data is processed here, and all callbacks are called from here |
Functions | |
_TCPServer_Create | Create a TCP server |
_TCPServer_Start | Starts the server |
_TCPServer_Stop | Stops the server |
_TCPServer_IsStarted | Return server status |
_TCPServer_Destroy | Destroy the server and free ressources |
Create a TCP server
_TCPServer_Create($sIP, $iPort, $iMaxClients = 50, $iClientPropertiesNbr = 0, $sPwd = "", $iTimeOut = 60)
$sIP | IP address to listen |
$iPort | Port number to listen |
$iMaxClients | Max number of simultaneous connected clients |
$iClientPropertiesNbr | Defines the number of properies that we can assigne for each client |
$sPwd | If specified, then the exchanged data between server and clients will be encrypted (must be the same as the client) |
$iCompressLvl | ZLib compression level, 0 - No compression, 9 - Max compression |
$iTimeOut | Client time-out (Seconds) |
1
Call this function ONLY ONE TIME in a script
Functions | |
_TCPServer_Config | Set server’s parameters |
_TCPServer_SetCallbacks | Set the callback functions that will be called when an event occurs |
Set server’s parameters
_TCPServer_Config($sIP = Default, $iPort = Default, $iTimeOut = Default, $iMaxClients = Default, $iClientPropertiesNbr = Default)
$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 |
1
Set the callback functions that will be called when an event occurs
_TCPServer_SetCallbacks($sCB_NewClient = Default, $sCB_LostClient = Default, $sCB_Recv = Default, $sCB_Receiving = Default, $sCB_TimedOut = Default)
$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 |
1
The syntax for each callback function is:
$iSocket | The socket ID of the client that is concerned by the event |
$sIP | the IP Address of the client |
$Data | The data received, either String or Binary (is it was sent) |
$iBufferLenght | Lenght 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.
Functions | |
_TCPServer_Send | Send data to a client |
_TCPServer_Broadcast | Send data to all connected clients |
_TCPServer_Disconnect | Disconnect a client |
_TCPServer_DisconnectAll | Disconnect all clients |
_TCPServer_GetBufferLen | Return the current buffer lenght of a client |
_TCPServer_SocketList | Return a list off all connected Socket IDs and their respective IP addresses |
_TCPServer_ClientCount | Return the number of currently connected clients |
Send data to a client
_TCPServer_Send($iSocket, $Data)
$iSocket | Socket ID of the client |
$Data | Data we want to send (See remark) |
Succes | Returns number of bytes sent. |
Failed | 0 and set @error to windows API WSAGetError return value (see http://msdn.microsoft.com |
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.
Send data to all connected clients
_TCPServer_Broadcast($Data)
$Data | Data we want to send (See remark in _TCPServer_Send) |
1
Disconnect a client
_TCPServer_Disconnect($iSocket)
$iSocket | Socket ID of a client |
Succes | 1 |
Failed | 0 and set @error to windows API WSAGetError return value (see http://msdn.microsoft.com |
Return a list off all connected Socket IDs and their respective IP addresses
_TCPServer_SocketList()
None
Succes | 2-D array with: - $array[0][0] = number of elements in the list (number of connected clients) |
Failed | 0 and set @error to -1 if the server isn’t started |
Functions | |
_TCPServer_SocketID2IP | Convert Socket ID to IP Address |
_TCPServer_IP2SocketID | Convert an IP Address to Socket ID |
_TCPServer_SocketID2SocketHandle | Get the Socket Handle of the corresponding Socket ID |
_TCPServer_SocketHandle2SocketID | Convert Socket Handle to Socket ID |
Get the Socket Handle of the corresponding Socket ID
_TCPServer_SocketID2SocketHandle($iSocket)
$iSocket | Socket ID |
Sucess | Socket Handle, or -1 if the Socket ID isn’t currently connected (attributed to a client) |
Failed | 0 and set @error to |
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
Functions | |
_TCPServer_ClientPropertyGet | Return client’s property current value |
_TCPServer_ClientPropertySet | Set client’s propery value |
Return client’s property current value
_TCPServer_ClientPropertyGet($iSocket, $iProperty)
$iSocket | Socket ID of a client |
$iProperty | 0-based index of the property |
Succes | Value of the property |
Failed | 0 and set @error to |
Set client’s propery value
_TCPServer_ClientPropertySet($iSocket, $iProperty, $Value)
$iSocket | Socket ID of a client |
$iProperty | 0-based index of the property |
$Value | Value to assign |
Succes | 1 |
Failed | 0 and set @error to |
Functions | |
_TCPServer_Process | This function makes the server work, all data is processed here, and all callbacks are called from here |
This function makes the server work, all data is processed here, and all callbacks are called from here
_TCPServer_Process()
None
Sucess | 1 |
Failed | 0 and set @error to -1 if the server isn’t started |
This function must be called indefinitly in your main loop or with AdLibRegister