1

I was playing around with Java sockets and I was trying to trasnfer files from a server to client, however, when they get transfer they are corrupted. This is the code from the server:

DataInputStream input;
DataOutputStream ouput;
//these two variable are initialized somewhere else in the code.
private void downloadFile() {
    try {
        String fileName= input.readUTF();
        File f = new File(path + fileName);
        size= f.length();
        file= new FileInputStream(path+ fileName);
        ouput.writeLong(size);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = file.read(buffer)) > 0) {
            output.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

on the client side:

public void downloadFile(String fileName) {
    try {
        this.client= new Socket(ip,port);
        DataInputStream input= new DataInputStream(this.client.getInputStream());
        DataOutputStream ouput= new DataOutputStream(this.client.getOutputStream());

        output.writeUTF("DOWNLOAD");
        output.writeUTF(fileName);

        File f = new File(path+ fileName);
        file = new FileOutputStream(f);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = input.read(buffer)) > 0) {
            file.write(buffer, 0, len);
        }
        file.flush();
        file.close();
        this.client.close();
    } catch (Exception e) {
        System.out.println("something went wrong");
    }
}

I dont know what am I doing wrong, the file gets completely transfer but not correctly.

sarnold
  • 102,305
  • 22
  • 181
  • 238
Daniel
  • 2,484
  • 4
  • 27
  • 35

2 Answers2

3

on the server:

ouput.writeLong(size);

you dont seem to handle this on the client side, you just append it to the downloaded file as if it was part of the binary data.

yurib
  • 8,043
  • 3
  • 30
  • 55
1

It looks like you send the length of the file from the server to the client:

    ouput.writeLong(size);

but your client code never does anything with the transmitted size, so it takes up the first few bytes of the file.

sarnold
  • 102,305
  • 22
  • 181
  • 238