[英]How to timeout a read on Java Socket?
I'm trying to read items from a socket and I notice that if there is nothing on the stream of the socket it will stay at the read and back up my application.我正在尝试从套接字读取项目,我注意到如果套接字流中没有任何内容,它将停留在读取状态并备份我的应用程序。 I wanted to know if there was a way to set a read timeout or terminate the connection after a certain amount of time of nothing in the socket.
我想知道是否有办法设置读取超时或在套接字中没有任何内容一段时间后终止连接。
If you write Java, learning to navigate the API documentation is helpful.如果您编写 Java,学习浏览API 文档会很有帮助。 In the case of a socket read, you can set the timeout option, eg:
在套接字读取的情况下,您可以设置超时选项,例如:
socket.setSoTimeout(500);
This will cause the InputStream
associated with the socket to throw a SocketTimeoutException
after a read()
call blocks for one-half second.这将导致与套接字关联的
InputStream
在read()
调用阻塞半秒后抛出SocketTimeoutException
。 It's important to note that SocketTimeoutException
is unique among exceptions thrown by such read()
calls, because the socket is still valid;需要注意的是
SocketTimeoutException
在此类read()
调用抛出的异常中是唯一的,因为套接字仍然有效; you can continue to use it.你可以继续使用它。 The exception is only a mechanism to escape from the read and decide if it's time to do something different.
异常只是一种逃避读取并决定是否该做一些不同的事情的机制。
while (true) {
int n;
try {
n = input.read(buffer);
catch (SocketTimeoutException ex) {
/* Test if this action has been cancelled */
if (Thread.interrupted()) throw new InterruptedIOException();
}
/* Handle input... */
}
If this socket was created through a URLConnection
to perform a web request, you can set the read and connect timeouts directly on the URLConnection
before reading the stream:如果此套接字是通过
URLConnection
创建的以执行 Web 请求,则可以在读取流之前直接在URLConnection
上设置读取和连接超时:
InputStream createInputStreamForUriString(String uriString) throws IOException, URISyntaxException {
URLConnection in = new URL(uriString).openConnection();
in.setConnectTimeout(5000);
in.setReadTimeout(5000);
in.setAllowUserInteraction(false);
in.setDoInput(true);
in.setDoOutput(false);
return in.getInputStream();
}
Yes, there should be an override of Read() that accepts a timeout value.是的,应该有一个接受超时值的 Read() 覆盖。 By 'override' I am not suggesting anyone write one, I am pointing out that one of the overrides of the socket methods he is using takes a timeout value.
通过“覆盖”,我不是建议任何人写一个,我是指出他正在使用的套接字方法的覆盖之一采用超时值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.