输入流中的无限循环 [英] Infinite Loop in Input Stream

查看:108
本文介绍了输入流中的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从套接字服务器端接收的输入流中进行读取.我无法知道响应的大小,我正在读入字节数组,这是代码

I am reading from an input stream which I am receiving from a server side of a socket. I have no way of knowing what the size of my response will be and I am reading into a byte array this is the code

public static String readString(InputStream inputStream) throws IOException {

    ByteArrayOutputStream into = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    for (int n; 0 < (n = inputStream.read(buf));) {
        System.out.println("Got to this point n is "+n);
        into.write(buf, 0, n); 
    }
    into.close();
    System.out.println("passed this point");
    return new String(into.toByteArray(), AddATudeMessage.CHARENC); 
}

现在将数字11和235打印到控制台,因此我假设服务器仍在将输出写入输入流.但是它停留在235,似乎什么也没有发生.我尝试将主执行线程暂停多达20秒,这时我从服务器接收到241个字节,然后同一无限循环再次发生,任何人都知道发生了什么事情

write now the numbers 11 and 235 get printed to the console so I assume the server is still writing output into the input stream. it however gets stuck at 235 and nothing seemes to be happending. I tried pausing the main execution thread for as much as 20 seconds at which point i receive 241 bytes from the server and then the same infinite loop reoccurs anyone know what's going on

推荐答案

代码的结构方式只有在服务器关闭套接字后才能起作用.否则,您的一方永远无法知道服务器是否已完成或运行缓慢(或网络拥塞).

The way your code is structured, it can work ONLY IF the server closes the socket when it's done. Otherwise your side can never know if the server is done or is merely slow (or there's network congestion).

只有两种方法可以解决此问题:

There are only two ways to solve this problem:

  1. 让服务器先发送期望的长度,然后停止读取,并在收到指定的字节数后继续操作.
  2. 让服务器在完成后发送一个特殊的数据序列,一种普通数据中不会出现的EOF标记,您可以寻找它们来告诉您何时没有更多数据.

使用available()的解决方案是不正确的,因为如果接收缓冲区当前为空,但仍在传输数据,则它可以返回零.

Solutions using available() are incorrect because it can return zero if the receive buffer is currently empty but there is still data in transit.

这篇关于输入流中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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