Jump to content

Autoit TCP*() functions: how to use correctly (order)


rudi
 Share

Recommended Posts

Hi everybody, and a (late) Happy New Year!

Reading up the help files I'm not sure, if I got the steps to open / use / disconnect / shutdown the TCP services correctly, server and client side.

This is a basic draft, please correct me, if I missed something important, tx.

Server side:

TCPStartup() ; general startup of TCP services

$MainSocket = TCPListen(@IPAddress1, 12345) ; create a listening socket TCP:12345

If $MainSocket = -1 Then Exit ; what causes this to fail? (beside 1=wrong IP, 2=wrong socket) Socket already in use? missing OS rights? Firewall restrictions?

;Help file: Wait for and Accept a connection
; this loops, until a client connects to this server?
; After the loop was left (first connection was made from a client), what will happen to a 2nd (3rd, ... ) connection attempt of
; another client (or the same client), when "server side" this loop isn't "watching" for incoming connections?
Do
$ConnectedSocket = TCPAccept($MainSocket)
Until $ConnectedSocket <> -1

; $ConnectedSocket is now representing a handle for exactly *ONE* client connect caught within the do ... until loop above

; Get IP of client connecting
$szIP_Accepted = SocketToIP($ConnectedSocket)
; this is just informational. "Knowing" the client's IP address isn't required, is it?

While
$recv = TCPRecv($ConnectedSocket, 2048) ; reads data sent from the client currently connected

; If the receive failed with @error then the socket has disconnected
; Question: "...has disconnected", does that mean, that the client has closed the socket, or might this be a network error as well?
If @error Then ExitLoop

If $recv <> "" Then
         ; data were received, process them
else
         ; no data were received: Will the socket stay open infinitely, when no data travel the socket connection?
endif

Wend

; the While ... wend is exited, if $TCPRecv() returned -1:
; What is this check of $ConnectedSocket good for?
If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)

TCPShutdown() ; stop autoit script's TCP services

Client side:

TCPStartup()

$ConnectedSocket = TCPConnect($Server_IP, 12345) ; connect to the listening port TCP:12345, "waiting" at the server above
; for the client socket number a random, available high port nuber is choosen automatically?
if @error then exit ; 1=wrong ip, 2= wrong port. Connection refused?? (WSAECONNRESET = 10054 ??) Port closed?

; Now the client is connected to the server, and data can be send using the socket (?)

$SendThis="some data to be send to the server"
do
TCPSend($ConnectedSocket, $SendThis)
$Err=@error
if $Err then
     ; do some error handling. What might show up here? Connection reset by peer, eg? What else to take care of?
     exitloop
endif
; process more data to be send, if done, set $done=true
until $done

; the helpfile example ends here for tcpsend() function (?)

; same like server side, this one, to do a "clean socket disconnet", that makes the server "recognize", that the client "has disconnected" ?
If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)

TCPShutdown() ; will close down the Autoit used TCP services.
; Will a TCPShutdown() without TCPCloseSocket() make the server recognize the "client disconnected" situation?

Regards, Rudi.

Edited by rudi

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to comment
Share on other sites

Hi,

You are asking questions on Windows TCP functions, you should search on msdn to get answers.

"Socket already in use?" ;yes

"this loops, until a client connects to this server?" ;yes
'After the loop was left (first connection was made from a client), what will happen to a 2nd (3rd, ... ) connection attempt of another client (or the same client), when "server side" this loop isn''t "watching" for incoming connections?' ;they won't be able to connect

'this is just informational. "Knowing" the client''s IP address isn''t required, is it?' ;it depends on your purposes

'If the receive failed with @error then the socket has disconnected
; Question: "...has disconnected", does that mean, that the client has closed the socket, or might this be a network error as well?' ;both

"no data were received: Will the socket stay open infinitely, when no data travel the socket connection?" ;yes, until on side disconnects

"TCPCloseSocket($ConnectedSocket)" ;only close the socket if you catch an @error on TCPSend/Recv
;and always close it after your loop if it's not already done.

Br, FireFox.

Edited by FireFox
Link to comment
Share on other sites

Hi FireFox,

thanks for your reply.

'this is just informational. "Knowing" the client''s IP address" isn''t required, is it?' ;it depends on your purposes

; to be able to receive data server side the socket connection is sufficent (Knowing the client IP might be nice, but isn't required)

'If the receive failed with @error then the socket has disconnected
; Question: "...has disconnected", does that mean, that the client has closed the socket, or might this be a network error as well?' ;both
; How to distinguish a "clean disconnect" from a "network error occured"?

"no data were received: Will the socket stay open infinitely, when no data travel the socket connection?" ;yes, until on side disconnects
; "one side disconnects", that basically is one side uses a "TCPCloseSocket()" ?
; Does a "TCPShutDown() include a "clean" disconnect?

"TCPCloseSocket($ConnectedSocket)" ;only close the socket if you catch an @error on TCPSend/Recv
;and always close it after your loop if it's not already done

I don't get the last line:

When the Client has done "its send data" it's required to "hang up".

I thought, that client side a "TCPCloseSocket()" is the appropriate way to "hang up" the socket connection to the server?

After client side a "TCPCloseSocket()" was done, the server is still "sitting there with an open socket connection" ??

So after this was done client side, server side the socket remains open, but a ...

$recv = TCPRecv($ConnectedSocket,2048)

... will return an error. *IF* this error occures server side (after the client did a TCPCloseSocket()), a manual TCPCloseSocket() is required server side?

Regards, Rudi.

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to comment
Share on other sites

I don't get the last line:

When the Client has done "its send data" it's required to "hang up".

I thought, that client side a "TCPCloseSocket()" is the appropriate way to "hang up" the socket connection to the server?

If you close the socket on the client side, you will need to reconnect and the server will need to recreate a socket.

After client side a "TCPCloseSocket()" was done, the server is still "sitting there with an open socket connection" ??

So after this was done client side, server side the socket remains open, but a ...

... will return an error. *IF* this error occures server side (after the client did a TCPCloseSocket()), a manual TCPCloseSocket() is required server side?

Honestly I don't know. I'm not going to document myself on this, but I think that it's better to do a close socket (for your second question). In the worst case it won't do anything and in other cases there might be some ressources to free.

Br, FireFox.

Link to comment
Share on other sites

Hi, and thanks again for your reply.

One thing I don't know about sockets is, are they a "one-way-channel"?

Or is it possible to use this socket connection to also transfer data from the server back to the client? ("two-way-drive")

I'll try to play around to investigate this question, but maybe you (or someone else) already has the answer at his/her finger tipps?

Good night at half past Midnight, was an really interesting coding afternoon / evening, Rudi. ;)

<edit: grammar>

Edited by rudi

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to comment
Share on other sites

When you have an open socket between the client and server you can communicate both ways.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 3 years later...

With above example

1.Connection OK

2. Server close conntection: that mean Client keep invalid socket for this connection

3. Client send data with invalid socket: send OK, autoit didn't found error from this invalid socket with $Err = 0. Next step 4

TCPSend($ConnectedSocket, $SendThis)
$Err=@error
if $Err then
     ; do some error handling. What might show up here? Connection reset by peer, eg? What else to take care of?
     exitloop
endif

 

4.Client send new data with invalid socket: send Fail, now at second time autoit found error from this invalid socket with $Err <> 0

The same with way server receive, at second time, server found error.

So, How to check if a socket is connected/disconnected in autoit?

My message/data is real time. I can not send same data with two times.

please help.

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...