I am having problem reading image bytes in java socket. My iOS client is sending an image here, and it needs to read the total bytes and store that as image on the server end. It works very fine, when i tested through iOS simulator. Because, If I test in simulator, it sends the image upto 46,577 bytes. It reads all very quickly and properly. If I test the same code sending image from an iPhone device, its also sending around "45, 301 bytes", but socket code is able to read only some "21, 720 bytes", so only half of the image is coming, (or) sometimes it reads very less around "4,000 bytes" only.
I couldn't understand why it is not able to read the same size data coming from device only? Could someone please guide me on this to solve?
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()and usinginput.read() != -1as the while loop's terminating condition? BecauseInputStream.available()returns the no. of bytes that can be read without blocking; it doesn't necessarily indicate that the stream has ended. Something along the lines of:while((next = input.read()) != -1) { byteArrayOutputStream.write(next); } byte[] data = byteArrayOutputStream.toByteArray();InputStream in = null; try { int next; ByteArrayOutputStream out = new ByteArrayOutputStream(); while((next = in.read()) != -1) { out.write(next); } byte[] data = out.toByteArray(); } catch(IOException e) { //handle error }