如何从HttpsURLConnection创建Java非阻塞InputStream? [英] How to create a Java non-blocking InputStream from a HttpsURLConnection?

查看:149
本文介绍了如何从HttpsURLConnection创建Java非阻塞InputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个URL,用于在发布新消息时从聊天室流xml更新.我想将URL转换为InputStream并继续读取它,只要保持连接并且没有发送Thread.interrupt()即可.我遇到的问题是,当有内容要从流中读取时,BufferedReader.ready()似乎不正确.

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.

我正在使用以下代码:

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()"部分并直接读取行,则会阻止进一步的操作,直到读取行为止.

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.

我如何a)使buf.ready()返回true,或者b)以防止阻塞的方式执行此操作?

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

预先感谢, 詹姆斯

推荐答案

如何创建Java非阻塞InputStream

不能.您的问题体现了一个矛盾之处. Java中的流正在阻塞.因此,没有诸如非阻塞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()返回true.时期. InputStreamsReaders被阻止.时期.这里的一切都按设计工作.如果您希望与这些API并发使用,则必须使用多个线程.或Socket.setSoTimeout()及其在HttpURLConnection中的近关系.

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.

这篇关于如何从HttpsURLConnection创建Java非阻塞InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆