The first thing you must know is that TCPServer UDF is very simple and easy to use. You don't
have to care about handling many clients, as the data you want will reach you when you need it.
Don't worry about listening for every new client, checking if the client is active or sent some data.
When it happens, the UDF will tell you. When there is a new client, when someone disconnects
or when someone sends something, you will get it. Truly, you do not need even to call
TCPStartup() and TCPShutdown() functions.
Important note: At the moment you can't create more than one server in the same script.
However, you can pause and resume (read 'stop and start again') your server at any time in your
script, without having to reset the server settings. And of course you can have many clients (or
just one, it's your choice!) in the same server. Some users bypass it by creating different scripts
and running them on background.
So let's code?
Start including the script, of course.
#include "TCPServer.au3"
Done? Now tell the UDF which functions you want to call on these events. Please note that no
one of this parameters is mandatory. However, let's agree that you must use at least one to
create most of the servers.
_TCPServer_OnConnect("connected")
_TCPServer_OnDisconnect("disconnect")
_TCPServer_OnReceive("received")
We are coding, so it's worth to enable debug mode.
_TCPServer_DebugMode()
How many clients will we support?
_TCPServer_SetMaxClients(10)
Are you ready? Then open the server in port 8081.
_TCPServer_Start(8081)
Now we must create the connected(), disconnect() and received() functions that we mentioned on
the events above. Our idea is too simple: when a user connects, we greet him. When he says
something, we say "Ok, I understood". And when he leaves, we show a message box in the
server saying "I miss him.". Already know how to do it?
Func connected($iSocket, $sIP)
_TCPServer_Send($iSocket, "Hello,
how are you?")
EndFunc
Func received($iSocket, $sIP, $sData, $sPar)
_TCPServer_Send($iSocket, "Ok,
I understood.")
EndFunc
Func disconnect($iSocket, $sIP)
MsgBox(0, "", "I miss
him.")
EndFunc
As the last part, as we don't want the script to finish while the server is open (since the server
does not stuck on any While loop, it does not pause your script), we just add this:
While 1
Sleep(100)
WEnd
And that is all.
Now let's run this script. It was not tested with Windows telnet, so I can't say if it works or not. But
I can say it works with Linux telnet, since it's similar to NetCat when sending data (it sends each
line, and not each char). So it's better to download NetCat here,
opening command prompt and
entering: