Search code examples
delphitcpindy

Delphi with Indy 10 - Best approach for TCP communication


I am creating a client-server application using Delphi XE3 and Indy 10 (idTCPServer and idTCPClient).

Server side will show all connected clients, and I can select some clients on the list and send them commands or streams/files. For this I created a message queue, as sugested by Mr. Remy Lebeau. Here is what I am doing:

enter image description here

What I would like to know is:

  1. Is this a good approach for what I am trying to do?

  2. When one side starts read/writing, it expects other side to write/read? What if other side can't? Supose SERVER requests a file, but it doesn't exists, must CLIENT write an "empty" stream anyway to avoid problems?

BTW, I can't find any good example of this (Indy 10 TCP Communication), using queue, error handling, etc. On Indy's website there are many broken links. Can you sugest me a website with good examples?

Thanks for any help!


Solution

  • When one side starts read/writing, it expects other side to write/read? What if other side can't? Supose SERVER requests a file, but it doesn't exists, must CLIENT write an "empty" stream anyway to avoid problems?

    Make the client send a reply accepting/rejecting the request before the file can then be transferred. Also make the receiver send a reply after the transfer is finished so the sender knows whether the whole file was received or not on the receiver's end.

    Server: I will send a file
    Client: OK
    Server: FileStream
    Client: OK
    

    Server: Send me a file
    Client: OK
    Client: FileStream
    Server: OK
    

    Server: I will send a file
    Client: Not Ready
    

    Server: Send me a file
    Client: Not Found
    

    Server: Send me a file
    Client: OK
    Client: FileStream (error midway)
    Server: FAILED
    

    With that said, since your server is the one sending commands to a client, consider using TIdCmdTCPClient on the client side instead of TIdTCPClient. That will provide you with a dedicated thread to receive the server commands, and you can create OnCommand handlers for your commands and use the provided TIdCommand objects to send replies.

    Consider using the TIdTCPConnection.SendCmd() method to send commands and read their initial responses, and TIdTCPConnection.GetResponse() to read the final responses.