0

Good evening, I'm writing a music service on Java where a Server Machine has music files, over a socket a client machine connects and then proceed to download the selected song.

While using the same machine for server-client operation the file transfer is completed and is played completely.

But when using different machines the file is allocated at its full size but the contents are empty, only the first or 2 seconds of the song are actually played.

Here is the Code for the Server:

//dos = DataOutputStream();
//song = path received thru dos.writeUTF(string);

File file = new File(song);
dos.writeUTF(file.getName());
dos.flush();
FileInputStream fin = new FileInputStream(file); 
int size = (int) file.length();
byte b[] = new byte[size];
int read;
dos.writeUTF(Long.toString(size));
dos.flush();
System.out.println("Size: " + size);
System.out.println("Buf size: " + s.getReceiveBufferSize());
while ((read = fin.read(b)) != -1) {
    dos.write(b, 0, read);
    dos.flush();
}
fin.close();
while (dis.available() > 0);

And this is for the client:

//dis = DataInputStream();
dos.writeUTF(p.toString()); //Send the path of the file that wants to download
song = dis.readUTF();
System.out.println("Receving file: " + song);
System.out.println("Saving as file: " + song);
int sz = Integer.parseInt(dis.readUTF());
System.out.println("Receiving " + sz + " bytes of data");
System.out.println("File Size: " + (sz / (1024 * 1024)) + " MB");
byte b[] = new byte[sz];
System.out.println("Receving file..");
FileOutputStream fos = new FileOutputStream(new File(p.getFileName().toString()), true);
long bytesRead;
do {
    bytesRead = dis.read(b, 0, b.length);
    fos.write(b, 0, b.length);
} while (!(bytesRead < sz));
System.out.println("Comleted");
fos.close();

Shall you need the complete code, here is the github: AntDraws13/MusicServer

I know that sending files this way is inefficient and insecure but this is only for a school project, Thanks!

user207421
  • 305,947
  • 44
  • 307
  • 483
Isaí Hinojos
  • 172
  • 2
  • 11
  • `while (dis.available() > 0);` is complete nonsense. It will either do nothing or loop forever. See my answer in the duplicate, even if you are only sending one file. – user207421 Mar 11 '19 at 02:12
  • I was using the while loop to clear data still in the stream, but it is now working thanks to your implementation, thanks. – Isaí Hinojos Mar 11 '19 at 03:11
  • But it *doesn't* 'clear all data still in the stream': it just loops forever; and if there is any data still in the stream it is a protocol error on your part, not something you should bodge around. – user207421 Mar 11 '19 at 03:27
  • So in case that I need to clear the stream without closing it, how should I do that? is it enough with flsuh or also reset? – Isaí Hinojos Mar 12 '19 at 04:35

0 Answers0