2

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

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

但它总是读取 readBytes 少于 i。而且我确信客户端会发送整个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;
    }
}

有任何想法吗?

4

1 回答 1

7

这:

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

应该:

read = inputStreamFromClient.read(b, threshold, b.length - threshold);
于 2012-05-11T22:17:29.090 回答