基本上,我有一个URL,当聊天室发布新消息时,它会流式传输xml更新。 我想将该URL转换为InputStream,并在连接保持的同时继续从中读取,只要我没有发送Thread.interrupt()。 我遇到的问题是,当流中有内容可读取时,BufferedReader.ready()似乎不会变为true。
我正在使用以下代码:
BufferedReader buf = new BufferedReader(new InputStreamReader(ins));
String str = "";
while(Thread.interrupted() != true)
{
connected = true;
debug("Listening...");
if(buf.ready())
{
debug("Something to be read.");
if ((str = buf.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
urlContents += String.format("%s%n", str);
urlContents = filter(urlContents);
}
}
// Give the system a chance to buffer or interrupt.
try{Thread.sleep(1000);} catch(Exception ee) {debug("Caught thread exception.");}
}
当我运行代码并向聊天室发送消息时,buf.ready()从未变为true,导致这些行永远不会被读取。但是,如果跳过"buf.ready()"部分,直接读取行,它会阻止进一步的操作,直到行被读取。
我该怎么做才能让buf.ready()返回true,或以一种防止阻塞的方式完成此操作?
提前感谢, 詹姆斯