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!