程序挂在while循环中,用于从套接字读取输入流:Java [英] program hangs inside while loop for reading input stream from socket: Java

查看:62
本文介绍了程序挂在while循环中,用于从套接字读取输入流:Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码从套接字连接读取输入流:

I have the following code to read an input stream from a socket connection:

private ByteBuffer toByteBuffer(BufferedInputStream is) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int l;
    byte[] data = new byte[256];
    while ((l = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, l);
    }
    buffer.flush();
    return ByteBuffer.wrap(buffer.toByteArray());
}

在while循环的第一次迭代中,一切正常,我能够将数据放入缓冲区.但是然后它卡在 while((l = is.read(data,0,data.length))!= -1){

In the first iteration of the while loop, everything goes fine and I am able to get the data into the buffer. But then it gets stuck at while ((l = is.read(data, 0, data.length)) != -1) {

我认为(而且我可能错了),这是因为它正在等待来自套接字的更多数据,而这永远不会发生.

I think (and I might be wrong) it is because it is waiting for more data from the socket, which is never going to come.

如何处理这种情况/挂起?

How do I handle this situation/hang?

推荐答案

由于您使用的 BufferedInputStream 方法不会阻止您得到 InputStream 没有任何数据,并且没有关闭,您不会得到-1而是0.这将使您的方法陷入无限循环.

As the BufferedInputStream method you are using does not block you get the situation that as soon as your InputStream does not have any data and is not closed you don't get a -1 but a 0. This will send your method into an endless loop.

因此,对于读取本地流,最好检查 read()< = 0 ,因为通常可以足够快地获取数据.
最好的方法是确保有一个通过关闭流 eof .

So for reading local streams it is better to check for read() <= 0 as you usually get the data fast enough.
The best way is to make sure there is an eof by closing the stream.

这篇关于程序挂在while循环中,用于从套接字读取输入流:Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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