I am just trying to send some files from a socket and i am able to send those files without any interruption: also whether the size file is small or large that does not matter it sends like a charm.
But the problem in my case that is arising is the file that i sent is being corrupted, i.e. it is not playing like audio or video. I have already gone through this but it did not helped.
The code that I am using is below.
Server Side:
File file = new File( Environment.getExternalStorageDirectory(), "testingFile.mp4"); byte[] mybytearray = new byte[4096]; FileInputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException ex) { ex.printStackTrace(); } BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); OutputStream os; DataOutputStream dos = null; try { os = socket.getOutputStream(); dos = new DataOutputStream(os); dos.writeUTF(file.getName()); dos.writeLong(mybytearray.length); int read; while ((read = dis.read(mybytearray)) != -1) { dos.write(mybytearray, 0, read); } socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (dos != null) { dos.flush(); } } catch (IOException e) { e.printStackTrace(); } }
And the Client Side :
File file = new File( Environment.getExternalStorageDirectory(), "TEST SUCCESS.mp4"); InputStream in = null; int bufferSize; try { bufferSize = socket.getReceiveBufferSize(); in = socket.getInputStream(); DataInputStream clientData = new DataInputStream(in); String fileName = clientData.readUTF(); System.out.println(fileName); OutputStream output = new FileOutputStream( file); byte[] buffer = new byte[bufferSize]; int read; while ((read = clientData.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (in != null) { in.close(); } }
Thanks in advance.
Advertisement
Answer
So after the conversations in comments and as @MarquisofLorne told to delete the line that i have written in my server side code. i.e either delete this line from server side code:
dos.writeLong(mybytearray.length);
or write this below line code in client side code:
long sizeOfFile = clientData.readLong();
It solves the problem.