0

I'm having trouble writing a server-client communication passing a bitmap as data.

At my server side I have

InputStream in = rs.getBinaryStream(1);
                        ByteArrayOutputStream f2 = new ByteArrayOutputStream();
                        int c = 0;
                        while ((c = in.read()) > -1) {
                            f2.write(c);
                        }
                        bytes = f2.toByteArray();
                        username2.write(bytes, 0, bytes.length);

And at my Android client, I have

 ByteArrayOutputStream out = new ByteArrayOutputStream();
            final byte[] buffer = new byte[2048];
            int read = -1;

            while ((read = receiveimagem.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }

The problem is, the client just understands that the sending is over when I close the outputStream at server side. But the structure is inside a loop and if I close the socket, it won't work again. How can I tell the client that the data is over? The code stucks in the Android client at the while. I know I should send the length and check it, but I don't know how to use the length to check the end of the file.

1 Answers1

-1

Your main problem in communicating the length of the image to the client is that the server itself doesn't know the length of the input before it begins transmitting the image. The server should read the entire image into a buffer first, then send the buffer's length to the client. The client can then execute a for loop, using the received size in the for loop's condition. A better solution would be for the client to read all of the image in one call, so you don't need to loop in the client. Doing I/O one byte at a time generally can and should be avoided. Also remember to flush both the output streams!

Daniel O
  • 336
  • 2
  • 3
  • 8
  • Reading in one call will not solve this problem. A read can transfer as little as one byte at a time. It is not guaranteed to fill the buffer. – user207421 Jun 16 '16 at 23:21
  • I have tried to get the ByteArray size through bytes.lenght and send it to the client. At the client side, after getting the size, how can I make this for loop? – Augusto Perucello Jun 16 '16 at 23:32
  • Thank you. Reading what you said, I could come out with a solution. Just made a for(int i=0, i<(lenght got from server), i++). Thank you so much. Also made final byte[] buffer = new byte[1]; so I can count it one by one – Augusto Perucello Jun 16 '16 at 23:38
  • @user3318082 There is no need to read one byte at a time. It could hardly be less efficient. You should read into a byte array of reasonable size, say 8k, and use the count returned by `read()` to tell you how much data was actually read. See my answer in the duplicate for how to do this under the control of an overall target length. – user207421 Jun 17 '16 at 06:02