开发者

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

I have an Android application where I'm trying to send a picture to a server. I did this using Base64 encoding a开发者_Go百科nd 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.


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[]{};
}


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;
 }


If you want bi-directional communication, the server must know when you're ready - you should prepend a 4 byte length field to your sender side indicating the number of bytes to come.

On the server side you read the length and then stay listening until everything has arrived. Then you can reply your acknowledge string.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜