java - 从 InputStream 读取到 byte[] 会抛出 IndexOutOfBoundsException

标签 java sockets networking inputstream

我显然不知道问题出在哪里!,首先我要求客户端向我发送他要发送的byte[]的长度,然后我读取它的长度,例如这个。

int i = 323292; // length of incoming Byte[]
byte[] b = new byte[i]; 
int readBytes=inputStream.read(b,0,b.length);

但是它总是读取小于i的readBytes。我确信客户端发送了整个 byte[]

我试图将它放在一个循环中,读取直到我的读取字节总数为 i,但在第二次迭代后我总是得到 IndexOutOfBoundsException!这是代码

boolean flag = true;
int i = 323292;
int threshold = 0;
byte[] b = new byte[i];
int read = 0;
while (flag) {
    if (threshold < i) {
        System.out.println(threshold);
        try {
            read = inputStreamFromClient.read(b, threshold, b.length);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        threshold = threshold + read;
    } else {
        flag = false;
    }
}

有什么想法吗?

最佳答案

这个:

read = inputStreamFromClient.read(b, threshold, b.length);

应该是:

read = inputStreamFromClient.read(b, threshold, b.length - threshold);

关于java - 从 InputStream 读取到 byte[] 会抛出 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10559292/

相关文章:

java - Java中的多线程服务器程序

java - IP 数据报中有效负载/数据的大小是如何决定的

java - java中有没有类似于swift的dynamicType的关键字

java - 在 Java 中使用反射查找枚举类

c# - 我的 .Net 套接字处理程序丢失数据包

c++ - C中使用读写函数的套接字错误

android - 如何通过 Android 连接网络打印机?

java - JsonMappingException : Can not instantiate value of type no single-long-arg constructor/factory method

java - 高枕无忧 - 使用 RestAssured 进行测试时出现操作超时错误。但相同的端点在浏览器中工作正常

java - 与 Jackson 通过 Socket 进行 Json