Setting a timeout for socket operations

2019-01-02 23:27发布

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?

标签: java sockets
5条回答
唯我独甜
2楼-- · 2019-01-02 23:39

You could use the following solution:

SocketAddress sockaddr = new InetSocketAddress(ip, port);
// Create your socket
Socket socket = new Socket();
// Connect with 10 s timeout
socket.connect(sockaddr, 10000);

Hope it helps!

查看更多
小情绪 Triste *
3楼-- · 2019-01-02 23:40

You can't control the timeout due to UnknownHostException. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.

But I find it hard to believe that you are really getting an UnknownHostException when you specify an IP address rather than a hostname.

EDIT To control Java's DNS timeouts see this answer.

查看更多
太酷不给撩
4楼-- · 2019-01-02 23:43

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

查看更多
别忘想泡老子
5楼-- · 2019-01-02 23:47

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

查看更多
时光不老,我们不散
6楼-- · 2019-01-02 23:48

Use the default constructor for Socket and then use the connect() method.

查看更多
登录 后发表回答