简体   繁体   English

传输文件时,它们会被Java套接字损坏

[英]when transferring files they get corrupted with java sockets

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. 我正在玩Java套接字,我试图将文件从服务器传输到客户端,但是,当它们被传输时,它们已经损坏。 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. 我不知道我做错了什么,文件完全转移但不正确。

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. 你似乎没有在客户端处理这个,你只需将它附加到下载的文件,就像它是二进制数据的一部分。

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. 但是你的客户端代码从不对传输的大小做任何事情,所以它占用了文件的前几个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM