当我创建一个套接字时:
Socket socket = new Socket(ipAddress, port);
它抛出一个异常,这没关系,因为IP地址不可用。 (测试变量 where String ipAddress = "192.168.0.3"
and int port = 300
。)
问题是:如何将其设置为该套接字的超时?
当我创建套接字时,如何减少获得 UnknownHostException
并使套接字超时的时间?
最佳答案
使用 Socket()
constructor , 和 connect(SocketAddress endpoint, int timeout)
method而是。
在你的情况下,它看起来像:
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);
引用文档
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 socketSince: 1.4
关于java - 设置套接字操作的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4969760/