16

When my Tcpclient is working , with this code :

TCPClient.Disconnect;
TCPClient.Connect;

I get "raised exception class EIdAlreadyConnected with message 'Already connected.'." error still (whereas , it has been disconnected before) .

So , how can i disconnect it totally ?

Thank you

Kermia
  • 4,171
  • 13
  • 64
  • 105

3 Answers3

20

using at indy 10 you must sure inputbuffer is empty.

if idTcpClient.connected then
begin
 idTcpClient.IOHandler.InputBuffer.clear;
 idTcpClient.Disconnect;
end;
sabri.arslan
  • 548
  • 2
  • 14
  • 8
    To elaborate, the Connected() method considers a connection to still be open, even if the physical socket has been closed, if the InputBuffer still has pending unread data in it that can satisfy read requests without going back to the socket. This is by design. Typically, you would disconnect the socket only after you have read all of the data that the connection has to offer. If you are disconnecting prematurely, then you have to clear any already-received-but-unread data manually by clearing the InputBuffer. – Remy Lebeau Aug 26 '10 at 21:03
  • And make sure that no "LINGER" socket options are set? – Marco van de Voort Oct 17 '11 at 11:17
  • 2
    Shouldn't you clear the buffer *after* it's been disconnected? Because suppose it receives some data in-between the time it clears and the time it disconnects? – Jerry Dodge Jun 29 '12 at 16:37
  • I too would like to know if the order in the example is correct (first clear, then disconnect)? – StanE May 22 '15 at 13:02
  • Order should be reverted, I've encountered this problem today. (Delphi XE5) – Wodzu Apr 04 '17 at 10:29
  • As i remembered, if you don't care about buffer then you should clear the buffer before disconnect, but the indy might be corrected this issue because i wrote this solution for Delphi 7 and the indy version as i remember was 9 – sabri.arslan Apr 10 '17 at 09:14
2

You say it is disconnected, but you only gave the command to disconnect.

Network traffic takes time, and probably you reconnected before you were really disconnected.

Probably you need to monitor some connection state or event to wait till you really are disconnected.

... or try to process the exception and ignore it, using try..except

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
  • 1
    Indy does *not* use asynchronous communication, so intuition would be that when the command returns it has already done its job. – jpfollenius Aug 27 '10 at 11:51
  • The problem is the definition of the job. The sending of the disconnect, or it being confirmed/timeout so that it is fully shutdown. – Marco van de Voort Aug 27 '10 at 13:03
1
TCPClient.IOHandler.InputBuffer.Clear;
TCPClient.IOHandler.CloseGracefully;
TCPClient.Disconnect;
Massimo Fazzolari
  • 5,185
  • 3
  • 27
  • 36