How to set Socket timeout of fail connecting

2019-03-04 18:19发布

问题:

Im trying to connect to socket socket = new Socket(server , port);, but if the server is not availabe I need to set a timeout of fail connection. Default timeout is 3min , for example if i start connecting in 11:50:22, error will be present only in 11:53:31. See log:

    12-03 11:50:22.519: E/InternetIntentService(23897): Start connecting to localhost:9999
    12-03 11:53:31.869: W/System.err(23897): java.net.ConnectException: failed to connect to /localhost (port 9999): connect failed: ETIMEDOUT (Connection timed out)

How to change this 3min to 10sec?

回答1:

Create a Socket with the no-args constructor and then call connect(endpoint, timeout);:

Socket s = new Socket();
s.connect(endpoint, timeout);

Note that contrary to the Javadoc, zero doesn't mean infinity, it means the platform default (around a minute), and that you can only use this technique to decrease the platform default, not to increase it.