我有阅读Java插座中的图像字节的问题。我的iOS客户端在这里发送图像,它需要读取总字节数并将其作为图像存储在服务器端。 它工作得很好,当我通过iOS模拟器测试。因为,如果我在模拟器中测试,它会将图像发送到46,577字节。它读取所有非常迅速和正确。如果我测试相同的代码从iPhone设备发送图像,其还发送关于“45,301字节”,但插座代码能够只读一些“21,720字节”,所以只有一半的图像(或)有时读起来非常少“4,000字节”只。无法使用InputStream读取API读取所有字节?
我不明白为什么它不能够读取相同大小的数据仅装置来吗?有人能指导我解决这个问题吗?
InputStream input = socket.getInputStream();
byte[] data = new byte[0];
byte[] buffer = new byte[1024];
try {
do {
bytesRead = input.read(buffer);
System.out.println("Reading..bytesRead: " + bytesRead);
// construct an array large enough to hold the data we currently have
byte[] newData = new byte[data.length + bytesRead];
// copy data that was previously read into newData
System.arraycopy(data, 0, newData, 0, data.length);
// append new data from buffer into newData
System.arraycopy(buffer, 0, newData, data.length, bytesRead);
// set data equal to newData in prep for next block of data
data = newData;
} while (input.available() != 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("data: " + data.length);
你可以尝试用'input.read()'一次读取一个字节,并使用'input.read()!= -1'作为while循环的终止条件?因为'InputStream.available()'返回no。可以无阻塞地读取的字节数;它并不一定表示该流已结束。 (while((next = input.read())!= -1){byteArrayOutputStream.write(next); } byte [] data = byteArrayOutputStream.toByteArray(); ' –
我无法做到这一点。你能请给出完整的样品吗? – Stella
我尝试了你的建议。 byte [] data = new byte [16384]; ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); while((nRead = input.read(data,0,data.length))!= -1)012B\t \t byteBuffer.write(data,0,nRead); byte [] dataOut = byteBuffer.toByteArray();客户端不停地循环发送数据,经过一段时间后,套接字全部读取并崩溃客户端应用程序。 – Stella