Java / Android: reading / writing a byte array over a socket

I have an Android app where I am trying to send an image to a server. I did this using Base64 encoding, and it worked pretty well, but it took too much memory (and time) to encode it before sending it.

I am trying to disconnect an Android application to the point where it simply sends an array of bytes and does not work with any encoding scheme, so it will save as many memory and processor cycles as possible.

Here is what I would like for the Android code to look like this:

public String sendPicture(byte[] picture, String address) { try { Socket clientSocket = new Socket(address, 8000); OutputStream out = clientSocket.getOutputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); out.write(picture); return in.readLine(); } catch(IOException ioe) { Log.v("test", ioe.getMessage()); } return " "; } 

The server is written in Java. How to write server code so that I can correctly get the same byte array? My goal is to save as many CPU cycles on Android as possible.

So far, all the methods I tried have led to corrupted data or thrown exceptions.

Any help would be appreciated.

+6
java android
source share
3 answers

Based on comments from Robert and Zaki, here is a modified code that should work better.

 public byte[] getPicture(InputStream in) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int length = 0; while ((length = in.read(data))!=-1) { out.write(data,0,length); } return out.toByteArray(); } catch(IOException ioe) { //handle it } return null; } 
+2
source share

Try something like this:

 public byte[] getPicture(InputStream in) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); int data; while ((data = in.read())>=0) { out.write(data); } return out.toByteArray(); } catch(IOException ioe) { //handle it } return new byte[]{}; } 
+3
source share

If you need bidirectional communication, the server should know when you are ready - you must add a 4-byte field to your sender side, indicating the number of bytes.

On the server side, you read the length, and then keep listening until everything comes along. Then you can answer your confirmation line.

If it is enough to send only the image, you can simply send data and close the connection. The server side is implemented as @thejh shows.

0
source share

All Articles