Making an application a TCP/IP Client...

Connecting to a TCP/IP Server from a Delphi client

In order to make a Delphi Application as a TCP/IP Client, we can use the TClientSocket Component.



I faced a problem when I try to connect to a TCP/IP server (another computer) and send data to that machine and get data back.



In form's OnShow event, I set the Address and Port properties of the TclientSocket component to the TCP/IP server's IP Address and Port Number and set Active to true. After that I tried to send the data in the same event. I was not able to send the data. I found that the Active property as True(meaning connected).



So I thought the problem could be with the form's OnShow event; Then I put the same code (setting the IP address and port number and active to true) in FormCreate/OnClick event; I was not able to come out of that problem.



The thing is that I did try to connect to the TCP/IP server and try to send the data at the same time. This doesn't seem to work properly. After that I referred the Delphi Help carefully and got the solution.



The Solution I found is:



First we need to set the IP Address/Port Number of the TCP/IP server in the Tclientsocket component properties in the main form's OnCreate event of the project and set Active to true. After that we can use the Open and Close methods of the TclientSocket component to connect/disconnect the TCP/IP server.



If we wish to send data to a TCP/IP server often from different forms in a project, we can use a DataModule and put a TclientSocket component in it and use it everywhere throughout the project by including that datamodule in all the unit files.



And one more thing, in the ClientSocketRead event we need to put some time delay while reading data back from the TCP/IP server. This time delay could be some milliseconds and depends on the network traffic since we may not read all the data sent from the TCP/IP server at a time even if you keep your buffer a large one. So you may need to wait for some milliseconds between reads.



I used the clienttype of the TclientSocket as ctNonBlocking; We can also use ctBlocking as clienttype; but in that case the TCP/IP server should be a threaded one.



Even though it seems to be a simple stuff, I just wanted to share with all of our friends in Delphi.



Enjoy!!!



Thanx.

Magesh.

 

Share this article!

Follow us!

Find more helpful articles: