简体   繁体   中英

Transfer a byte[] via TCP Socket in android

I need to transfer a byte[] via TCP Socket in android -client side.
i tried to use the following code :

public static int readBytes(byte[] myByteArray) throws IOException {
    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    int len = dis.readInt(); //<-here i get the error

    byte[] data = new byte[len];
    if (len > 0) {
        dis.readFully(data,0,len);
    }
    myByteArray=data;
    return data.length;
}

but I get the following error:

12-23 17:30:49.814: E/AndroidRuntime(11717): java.lang.OutOfMemoryError: array size too large(Heap Size=5699KB, Allocated=3403KB, Bitmap Size=78KB)

See this answer. Java Heap Memory error from socket I wonder, is there some code example on Android that is leading people to this?

You probably get the OutOfMemoryError on the line below. (The line that allocates new memory using new .)

Print len before doing the allocation and you'll probably see that it's a huge number (a lot larger than what you expect).

Log.d("YOU_TAG", "len = " + len);

Presumably you don't send the size of the byte array on the sending side. (Or if you do, your reading / writing has come out of sync.)

you must read in a closed loop like this:

while(true){
int len = dis.readInt();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM