【发布时间】:2012-05-20 12:26:37
【问题描述】:
我显然不知道问题出在哪里!首先我要求客户将他要发送的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;
}
}
有什么想法吗?
【问题讨论】:
-
您真的应该使用 Commons IO 包之一来节省一些编码时间和不必要的复杂性:commons.apache.org/io/api-release/org/apache/commons/io/…
-
感谢您的帮助,我会检查它!
-
这个简单的任务不需要第三方软件。见
DataInputStream.readFully()。
标签: java sockets networking inputstream