基本上,當有新消息發佈時,我有一個從聊天室傳輸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