从Java输入流读取时有没有办法超时?
可能的重复:
是否可以从Java读取输入流超时?
我注意到,当我尝试读取更多信息然后发送到我的服务器时,网络浏览器会冻结。我看到我的套接字冻结了,因为网络浏览器返回的信息少于它尝试读取的信息。有没有办法在 Currtly 我正在使用输入流上设置超时
public String ReadLine()
{
String out;
out="";
// read in one line
try{
request = new StringBuffer(1000);
boolean f=true;
while(true)
{
int c=in.read();
if (c=='\r')
{
// next should be a \n
// Program freezed hear
c=in.read();
if (f==true)
return "";
break;
}
f=false;
out=out+(char)c;
request.append((char)c);
} // end while
} catch(IOException ec)
{
System.out.println(ec.getMessage());
}
System.out.println(request);
return out;
}
Possible Duplicate:
Is it possible to read from a Java InputStream with a timeout?
I noticed that when I was trying to read in more information then was sent to my server, the web browser would freeze. I saw that my socket froze, since the web browser was returning less information then it was trying to read. Is there a way to set out a time out on Currtly I’m using a input stream
public String ReadLine()
{
String out;
out="";
// read in one line
try{
request = new StringBuffer(1000);
boolean f=true;
while(true)
{
int c=in.read();
if (c=='\r')
{
// next should be a \n
// Program freezed hear
c=in.read();
if (f==true)
return "";
break;
}
f=false;
out=out+(char)c;
request.append((char)c);
} // end while
} catch(IOException ec)
{
System.out.println(ec.getMessage());
}
System.out.println(request);
return out;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Socket.setSoTimeout()
或HttpURLConnection.setReadTimeout()
。Socket.setSoTimeout()
orHttpURLConnection.setReadTimeout()
.这里讨论过: 是否可能从具有超时的 InputStream 读取?
据我所知,提供了解决方案。
It was discussed here: Is it possible to read from a InputStream with a timeout?
As far as I can see, the solution is provided.
你有几个选择,但并不漂亮。 “普通”java套接字io没有超时,流也没有
在单独的线程中进行读取并对输入数据进行排队
使用您自己的超时机制
使用java非阻塞IO api
http://download.oracle.com/javase/1.4 .2/docs/guide/nio/
you have a couple of choices but it isn't pretty. the 'normal' java socket io doesn't have timeouts nor do the streams
do your reading in a separate thread and queue up the input data
with a timeout mechanism of your own
use java nonblocking IO api
http://download.oracle.com/javase/1.4.2/docs/guide/nio/