Best practice: Keep TCP/IP connection open or close it after each transfer?

Holgerwa picture Holgerwa · Feb 17, 2011 · Viewed 13.6k times · Source

My Server-App uses a TIdTCPServer, several Client apps use TIdTCPClients to connect to the server (all computers are in the same LAN).

Some of the clients only need to contact the server every couple of minutes, others once every second and one will do this about 20 times a second.

If I keep the connection between a Client and the Server open, I'll save the re-connect, but have to check if the connection is lost.

If I close the connection after each transfer, it has to re-connect every time, but there's no need to check if the connection is still there.

What is the best way to do this?

At which frequency of data transfers should I keep the connection open in general?

What are other advantages / disadvantages for both scenarios?

Answer

Remy Lebeau picture Remy Lebeau · Feb 17, 2011

I would suggest a mix of the two. When a new connection is opened, start an idle timer for it. Whenever data is exchanged, reset the timer. If the timer elapses, close the connection (or send a command to the client asking if it wants the connection to remain open). If the connection has been closed when data needs to be sent, open a new connection and repeat. This way, less-often-used connections can be closed periodically, while more-often-used connections can stay open.