autopilot
autopilot

Reputation: 31

connect() method ignoring its timeout value

I'm developing an application for Android that requires sending messages over a TCP socket connection. I have set a timeout value as per the connect(SocketAddress endpoint, int timeout) method. Now the connect() method blocks till the timeout expires and a SocketException is thrown only if the server is offline. In all other cases like network disabled, network unreachable, etc the timeout value is being ignored and the method directly throws a SocketException (ENETUNREACH). How do I make sure the timeout works even in such cases? Will supply additional information if required.

Thanks

Upvotes: 1

Views: 529

Answers (2)

Stephen C
Stephen C

Reputation: 718678

The connect timeout is for the case where the you get no response from the remote server. In other cases the timeout doesn't apply; e.g.

  • when the connection succeeds,
  • when the remote server refuses the connection,
  • when the networking layer says "no route to host"
  • when the networking layer says "no route to network" / "network unreachable".

In these cases, the connect attempt succeeds or fails immediately. If you want to keep trying, you need to wrap the connect call in some code that will retry in the event of a retryable failure. (And it is up to you to write the code to decide how often to retry, and when to stop, so as not to waste network resources, battery charge, etc.)

Upvotes: 5

s.d
s.d

Reputation: 29436

That is the intended behavior of the method. Timeout is only relevant when establishing connection takes time. If it is determined that the connection cannot be established due to other reasons, error will be thrown immediately, without wasting time. That's how the method is implemented internally.

Upvotes: 0

Related Questions