java - 设置套接字操作的超时

标签 java sockets

当我创建一个套接字时:

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 socket

Since: 1.4

关于java - 设置套接字操作的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4969760/

相关文章:

c# - 使用 Receive[...]Async 方法时获取远程端点信息 - 仅供引用

android - 套接字总是收到最后一个 udp 数据包

java - compareTo 方法如何在这里对对象进行一一排序

java - 对创建一副纸牌的一点帮助

java - 从 java 内部调用 node.js 脚本

C++ 套接字 : size of the structure addrinfo

java - 实现套接字连接的servlet

linux - 监听Socket并复制到另一个端口

java - 连续监听 AWS SQS 消息的模式

java - 将同一项目 src 中的文件链接到 mediaPlayer