Indy “Connection Closed Gracefully” Errors

I was being plagued by “Connection closed gracefully” errors in an application that uses the Indy TIdHttp component to communicate with a remote server.  Periodically, I would get one of these exceptions.  Basically, this should be no big deal.  It just means that the remote server closed the connection before the transaction was complete.  i.e. I had sent the request but before I got the response, the remote server closed the connection.  So, just close the connection and try again after a suitable interval you say.  Well that is what I thought, but calling TIdHttp.Disconnect, waiting a bit and sending the request again just resulted in the same error over and over and over and over …

It turns out, that if there is any data left in Indy’s input buffer simply calling disconnect doesn’t actually get rid of the connection.  The connection lingers on until the input buffer is emptied.  In order to get rid of the connection completely you need to flush the input buffer by calling TIdHttp.IOHandler.InputBuffer.Clear after calling TIdHttp.Disconnect.  Completely inobvious and  not documented at all as far as I can tell.

Leave a Reply