Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

I have an Android application where I'm trying to send a picture to a server. I did this using Base64 encoding and it worked quite well, but it took too much memory (and time) to encode the picture before sending it.

I'm trying to strip the Android application down to where it just simply sends the byte array and doesn't fiddle around with any kind of encoding scheme so it'll save as much memory and CPU cycles as possible.

This is what I would like the Android code to look like:

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 do I write the server code so I can properly retrieve the exact same byte array? My goal is to save as many CPU cycles on the Android as possible.

So far, all the methods I've tried resulted in corrupt data or a thrown exception.

Any help will be appreciated.

like image 397
user489481 Avatar asked Jan 08 '11 12:01

user489481


2 Answers

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[]{};
}
like image 125
thejh Avatar answered Nov 09 '22 10:11

thejh


Based on Robert's and Zaki's comment, here is the modified code that should perform 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;
 }
like image 2
Droidman Avatar answered Nov 09 '22 09:11

Droidman