I am trying to send any file via TCP from my client (on a mobile device) to a console server (on a computer).
Connecting, sending, receiving, in my opinion, is normal, but there is a problem with writing data to a file.
For example, music is recorded into it several times, and only one “line” is recorded for a picture.
I suspect that the problem is somewhere in the cycle, but I can not understand for sure.
Server code in which the bytes are received from the socket and written to the file:
String fileName; int size; try { size = sInput.readInt(); fileName = sInput.readUTF(); try { FileOutputStream fos = new FileOutputStream("C:\\Users\\admin\\Downloads\\FileSenderDownload\\" + fileName); byte[] buffer = new byte[size]; int receivedBytes = 0; while (true) { if (receivedBytes == -1) break; receivedBytes = input.read(buffer); System.out.println(receivedBytes); fos.write(buffer, 0, buffer.length); } System.out.println("Запись"); } catch (IOException ex) { ex.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } Client code to send the file:
try { DataOutputStream out = new DataOutputStream(socket.getOutputStream()); ObjectOutputStream output= new ObjectOutputStream(socket.getOutputStream()); output.writeInt((int)sendingFile.length()); output.flush(); System.out.println("File size" + sendingFile.length()); output.writeUTF(sendingFile.getName()); output.flush(); System.out.println("File name" + sendingFile.getName()); FileInputStream input = new FileInputStream(sendingFile); int size = (int)sendingFile.length(); byte[] buffer = new byte[size]; int receivedBytes; while(true) { receivedBytes = input.read(buffer); if (receivedBytes == -1) { break; } if (receivedBytes > 0) { out.write(buffer, 0, receivedBytes); out.flush(); } } input.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } How to fix this code?