When I create a socket:
Socket socket = new Socket(ipAddress, port);
It throws an exception, which is OK, because the IP address is not available. (The test variables where String ipAddress = "192.168.0.3"
and int port = 300
.)
The problem is: how do I set it to timeout for that socket?
When I create the socket, how do I reduce the time before I get a UnknownHostException
and get the socket to timeout?
Re: Recommended Value for http socket timeout The parameter is http_socket_timeout.
The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.
SocketTimeoutException: Connection timed out) means that it takes too long to get respond from other device and your request expires before getting response.
The timeout value defines how long the ServerSocket. accept() method will block: ServerSocket serverSocket = new new ServerSocket(port); serverSocket. setSoTimeout(40000); Similarly, the timeout unit should be in milliseconds and should be greater than 0.
Use the Socket()
constructor, and connect(SocketAddress endpoint, int timeout)
method instead.
In your case it would look something like:
Socket socket = new Socket(); socket.connect(new InetSocketAddress(ipAddress, port), 1000);
Quoting from the documentation
connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.
Parameters:
endpoint
- the SocketAddresstimeout
- the timeout value to be used in milliseconds.Throws:
IOException
- if an error occurs during the connectionSocketTimeoutException
- if timeout expires before connectingIllegalBlockingModeException
- if this socket has an associated channel, and the channel is in non-blocking modeIllegalArgumentException
- if endpoint is null or is a SocketAddress subclass not supported by this socketSince: 1.4
You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.
For example socket.connect(otherAddress, timeout)
Or socket.setSoTimeout(timeout)
for setting a timeout on read()
operations.
See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With