【发布时间】:2011-02-19 06:41:21
【问题描述】:
基本上,我有一个 URL,可以在发布新消息时从聊天室流式传输 xml 更新。我想将该 URL 转换为 InputStream 并继续从中读取,只要保持连接并且只要我没有发送 Thread.interrupt()。我遇到的问题是当有内容要从流中读取时,BufferedReader.ready() 似乎不会成为真的。
我正在使用以下代码:
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()”部分并直接读取行,它会阻止进一步的操作,直到读取行。
我该如何 a) 让 buf.ready() 返回 true,或 b) 以防止阻塞的方式执行此操作?
提前致谢, 詹姆斯
【问题讨论】:
-
每个连接都应该分成一个单独的线程。
标签: java inputstream nonblocking