java urlconnection inputstream,如何从HttpsURLConnection创建Java非阻塞InputStream?

Basically, I have a URL that streams xml updates from a chat room when new messages are posted. I'd like to turn that URL into an InputStream and continue reading from it as long as the connection is maintained and as long as I haven't sent a Thread.interrupt(). The problem I'm experiencing is that BufferedReader.ready() doesn't seem to become true when there is content to be read from the stream.

I'm using the following code:

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.");}

}

When I run the code, and post something to the chat room, buf.ready() never becomes true, resulting in the lines never being read. However, if I skip the "buf.ready()" part and just read lines directly, it blocks further action until lines are read.

How do I either a) get buf.ready() to return true, or b) do this in such a way as to prevent blocking?

Thanks in advance,

James

解决方案

How to create a Java non-blocking InputStream

You can't. Your question embodies a contradiciton in terms. Streams in Java are blocking. There is therefore no such thing as a 'non-blocking InputStream'.

Reader.ready() returns true when data can be read without blocking. Period. InputStreams and Readers are blocking. Period. Everything here is working as designed. If you want more concurrency with these APIs you will have to use multiple threads. Or Socket.setSoTimeout() and its near relation in HttpURLConnection.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值