Timeout for InetSocketAddress

I have the following code:

socket.connect(new InetSocketAddress(serverHost, serverPort), CONNECT_TIMEOUT); 

The problem is that when DNS is not available, InetSocketAddress takes 45 seconds to time out and returns an exception ("Host in not available ..."). I need the whole command (so creating an InetSocketAddress and connecting to a timeout earlier. I have not found a way to timeout new InetSocketAddress(serverHost, serverPort) before.

Is it possible?

PS I am on Android, but the problem is the same on another platform

+4
source share
1 answer

There is no easy way. You need to run this code

 socket.connect(new InetSocketAddress(serverHost, serverPort), CONNECT_TIMEOUT); 

in a separate stream (input / output stream) and communicate with it from the main stream of the user interface. As soon as you finish your time limit - send him a signal of termination and immediately go to the user interface stream, do not wait until it ends. Depending on the state, the i / o stream either immediately dies or with time.

+1
source

Source: https://habr.com/ru/post/1469293/


All Articles