基本上,当有新消息发布时,我有一个从聊天室传输xml更新的URL。我希望将该URL转换为InputStream,并且只要保持连接并且只要我没有发送Thread.interrupt(),就可以继续读取它。我遇到的问题是BufferedReader.ready()在从流中读取内容时似乎不成立。如何从HttpsURLConnection创建Java无阻塞的InputStream?
我用下面的代码:
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()永远不会成为真正的,导致永远不会被读取的行。但是,如果我跳过“buf.ready()”部分并直接读取行,则会阻止进一步操作,直到读取行。
我该如何a)让buf.ready()返回true,或b)以防止阻塞的方式执行此操作?
由于提前, 詹姆斯
每个连接都应该拆分成一个单独的线程。 – Nick 2011-02-19 06:48:08