Building Multi threaded TCP/IP Server

DelphiDev picture DelphiDev · Feb 18, 2010 · Viewed 13.1k times · Source

I wanna build a TCP/IP server that will be used by up to 100 concurrent clients, but still not sure how to get started.

at least I need the server to this:

  1. Listening to client, and store all them on array or list.
  2. for each client, it need to receive and send data based on it's client status.
  3. The server should update the clients list when someone connect or disconnect.
  4. Prefer to work as service with GUI to manage it.

Could anyone help how to get start with that,I looked at indy sample but they didn't help, also looked for most components but still searching.

Answer

John Thomas picture John Thomas · Feb 18, 2010

You need to use the TidTCPServer which is multithreaded inside. No need for you to manage the threads. Everything is transparent, so in the way in which you write the application for one client, in (almost) the same way you will write it for many. See the OnConnect event. There is a TidContext parameter which has a TThreadList inside. You can use that event to 'register'/add your clients to your custom array/list and OnDisconnect to remove the clients.

The OnExecute event is triggered when the server receives a message. Use its parameters to read the message which is sent.

Also, you need another application which will be your client, using TidTCPClient. In this application you will set the address of your server (see the Host property) as well as the Port which should match with the server's one. You should call Connect (when the server is running) and to send strings you have SendCmd method. (Also see IOHandler.WriteLn if you want)

There are also other things but I think that's enough to get you started. Also you can post in Embarcadero's forums in the .Delphi.Winsock forum where the Indy team members are floating over. Or perhaps you can ask directly in .Delphi.Non-Technical and the guys there will guide you.

Another approach is DataSnap which is a more object-oriented layer over Indy (not to be confused with DBX) which gives your JSON, REST and other goodies. See for a small review here.