Android client sends a large file using Socket, the file received by the server is incomplete

I want to send a large file from Android to the server via a socket, but the file received by the server is incomplete.

Android Code:

Socket client = new Socket(ipStr, 4444); OutputStream outputStream = client.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); byte[] buffer = new byte[512]; byte[] sendLen = getBytes(file.length(), true); outputStream.write(sendLen); outputStream.flush(); int count; while ((count = fileInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, count); } outputStream.flush(); bufferedInputStream.close(); outputStream.close(); client.close(); 

Server Code:

 byte[] recvHead = new byte[8]; inStream.read(recvHead, 0, 8); long recvLength = getLong(recvHead, false); FileOutputStream file = new FileOutputStream(fileName, false); byte[] buffer = new byte[8192]; int count = 0; while (count < recvLength) { int n = inStream.read(buffer); if(n == -1) break; file.write(buffer, 0, n); count += n; } 

But the server will block reading (buffer) (android sended file is about 30M).

Here's the strange thing: When I add output to a file when sending the file, the server may work properly.

  FileOutputStream file2 = new FileOutputStream("/sdcard/testfile" , false); while ((count = fileInputStream.read(buffer)) >= 0) { outputStream.write(buffer, 0, count); outputStream.flush(); file2.write(buffer, 0, count); file2.flush(); } 

Can anybody help me? Thanks!

+4
source share
1 answer

You cannot assume that you are reading 8 bytes of length. You could read just one byte in an array of length. I would use DataInputStream.readLong () for this and DataOutputStream.writeLong () to write it. Or, when you close one file, completely get rid of the word length and just read before EOS.

The rest of the code looks OK. If the receiver blocks reading (), the data is still coming, and the sender is still sending.

+1
source

Source: https://habr.com/ru/post/1441962/


All Articles