Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a timeout for socket operations

Tags:

java

sockets

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?

like image 922
Jennifer Avatar asked Feb 11 '11 13:02

Jennifer


People also ask

What is a good socket timeout?

Re: Recommended Value for http socket timeout The parameter is http_socket_timeout.

What is socket read 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.

What is a socket timeout exception?

SocketTimeoutException: Connection timed out) means that it takes too long to get respond from other device and your request expires before getting response.

What is Java socket timeout?

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.


2 Answers

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 SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

like image 99
aioobe Avatar answered Sep 22 '22 23:09

aioobe


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

like image 37
payne Avatar answered Sep 22 '22 23:09

payne