簡體   English   中英

通過Java套接字發送文件

[英]Sending a file over java socket

我一直在搜索Google數小時,試圖弄清楚如何通過Java套接字成功發送任何文件。 我在網上發現了很多東西,但似乎對我都不起作用,我終於遇到了對象輸出/輸入流,以便在服務器和客戶端之間發送文件,這是迄今為止我發現的唯一可行的方法,但是似乎只能通過與本地主機的連接來工作。 例如,如果我從另一個網絡上的朋友的計算機連接到服務器並發送文件,則文件失敗,套接字關閉並顯示“讀取超時”,然后在重新連接后不久,文件就再也不會發送。 如果我連接到服務器上的localhost並發送文件,則可以正常運行。 那么問題是什么,我該如何解決?

編輯:下面是更新的代碼。

public synchronized File readFile() throws Exception {
    String fileName = readLine();
    long length = dis.readLong();
    File temp = File.createTempFile("TEMP", fileName);
    byte[] buffer= new byte[1000];
    int count=0;
    FileOutputStream out = new FileOutputStream(temp);
    long total = 0;
    while (total < length && (count = dis.read(buffer, 0, (int)Math.min(length-total, buffer.length))) > 0)
    {
        System.out.println(total+" "+length+" "+temp.length()); //Just trying to keep track of where its at...
        out.write(buffer, 0, count);
        total += count;
    }
    out.close();
    return temp;
}


public synchronized void writeFile(File file) throws Exception {
    writeString(file.getName());
    long length = file.length();
    dos.writeLong(length);
    byte[] buffer= new byte[1000];
    int count=0;
    FileInputStream in = new FileInputStream(file);
    long total = 0;
    while (total < length && (count = dis.read(buffer, 0, (int)Math.min(length-total, buffer.length))) > 0)
    {
        System.out.println(total+" "+length); //Just trying to keep track of where its at...
        dos.write(buffer, 0, count);
        total += count;
    }
    in.close();
}

客戶端和服務器都具有writeFile和readFile。 目前,我正在使用它來發送和顯示圖像。

不要為此使用對象流。 使用DataInputStreamDataOutputStream:

  1. 使用writeUTF()readUTF()發送和接收文件名。
  2. 發送和接收數據,如下所示:

     while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } 

    您可以在兩端使用此代碼。 buffer大小可以大於零。 它不必是文件的大小,並且也不會縮放到大文件。

  3. 關閉插座。

如果您需要發送多個文件,或者需要保持套接字打開狀態:

  1. 使用writeLong()發送文件前面的長度,並使用readLong()讀取它並修改循環,如下所示:

     long length = in.readLong(); long total = 0; while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0) { out.write(buffer, 0, count); total += count; } 

    並且不要關閉插座。 請注意,您必須讀取測試total ,並且必須調整讀取長度參數,以免超出文件末尾。

暫無
暫無

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

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