簡體   English   中英

傳輸文件時,它們會被Java套接字損壞

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

我正在玩Java套接字,我試圖將文件從服務器傳輸到客戶端,但是,當它們被傳輸時,它們已經損壞。 這是來自服務器的代碼:

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();
    }
}

在客戶端:

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");
    }
}

我不知道我做錯了什么,文件完全轉移但不正確。

在服務器上:

ouput.writeLong(size);

你似乎沒有在客戶端處理這個,你只需將它附加到下載的文件,就像它是二進制數據的一部分。

看起來您將文件的長度從服務器發送到客戶端:

    ouput.writeLong(size);

但是你的客戶端代碼從不對傳輸的大小做任何事情,所以它占用了文件的前幾個字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM