简体   繁体   中英

Sending both a String and a Byte[] from Android app to Python Server over Sockets

I'm sending an image from an android app as a byte array. I was previously able to send the array in parts and then put those parts into a list in python but that created some errors because python would front load each part with b' and those would remain as part of the string. So I'm now trying to send the entire byte array. Before I send the array I send a String that gives the size of the Byte array so I can call call.recv for the proper size.

bytes_len = int(clean_len(str(connection.recv(1024))))

Where clean_len just takes out '\'' and 'b'

I then use data = connection.recv(int(bytes_len) But it outputs data as

Waiting on connection...
---------------------------------------------
Connection Accepted
Connection received from... ('192.168.1.89', 41568)
BYTES_LEN_RECV:  9640320 
METADATA_RECV:  m240,second_attempt,requalify,4,4,4
BYTE_ARRAY_RECV:  b'' #THIS IS THE ISSUE
Sending Response
Closing Connection to  ('192.168.1.89', 41568)

I'm sending the string like this from the app, it's closely followed by the byte array

printWriter.write(String.valueOf(bytes.length));
printWriter.flush();
printWriter.write(metadata);
printWriter.flush();
printWriter.close();

BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
bufferedOutputStream.write(bytes,0,bytes.length);
bufferedOutputStream.flush();
bufferedOutputStream.close();
socket.close();

Can you just not send byte arrays that long? Or am I missing some crucial unknown step?

Don't read the socket multiple times. Refactor the code so you take the raw bytes from the buffer first, then process the bytes any way that you like.

data = connection.recv(1024)
data = clean_data(data)
...

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