(11-14-2018, 05:56 AM)edwinyzh Wrote: how to abort the connection before the timeout value is reached?
Several events are triggered by
TIdTCPClient.Connect() (in this order):
-
OnBeforeBind
-
OnSocketAllocated
-
OnAfterBind
-
OnStatus(hsResolving) ¹
-
OnStatus(hsConnecting) ²
-
OnStatus(hsConnected)
-
OnConnected
You can raise an exception from any of those events.
¹ during the
hsResolving stage, there is currently no way to abort a hostname lookup. You just have to let it play out on its own. Otherwise, do your own lookup, such as via
TIdDNSResolver, and assign only IP addresses to
TIdTCPClient.
² The
ConnectTimeout properly applies to the
hsConnecting stage only. During that stage, to abort the connection prematurely, you must close the underlying socket directly (which is what
Connect() does when the timeout elapses). You can close the socket at any time after the
OnSocketAllocated event has been triggered, such as by calling
TIdTCPClient.Socket.Binding.CloseSocket() ³.
³ I suppose calling
TIdTCPClient.Disconnect() would also work, though it does
Close() the
IOHandler (which has threading issues for
TIdSSLIOHandlerSocketOpenSSL), and it also triggers the
OnStatus(hsDisconnecting),
OnDisconnected, and
OnStatus(hsDisconnected) events. I think for purposes of aborting a connection in progress, using
CloseSocket() would be a safer choice.