2014-11-25 234 views
0

我一直在Google上搜尋幾個小時,試圖瞭解如何通過java套接字成功發送任何文件。我在網上發現了很多東西,但它們都沒有爲我工作,我終於碰到了對象輸出/輸入流以在服務器和客戶端之間發送文件,這是迄今爲止我發現的唯一工作,但它似乎只能通過連接到本地主機。例如,如果我從不同網絡上的朋友計算機連接到服務器併發送失敗的文件,套接字將關閉,並顯示「讀取超時」,然後在重新連接後不久,文件就不會被髮送。如果我連接到服務器上的本地主機,併發送文件,它完美的作品。那麼最新的問題以及如何解決?通過Java套接字發送文件

編輯:以下是更新代碼..招式極爲緩慢

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。目前我正在使用它來發送和顯示圖像。

+0

什麼是您嘗試連接的套接字的IP地址和端口? – 2014-11-25 01:27:53

+0

可能被防火牆阻止。 – 2014-11-25 01:29:12

+0

我可以確認套接字能夠完美地連接到服務器,它只有發送文件有問題。 (它仍然讀取服務器發送的名稱和其他內容) – 2014-11-25 01:29:47

回答

2

請勿爲此使用對象流。使用DataInputStreamDataOutputStream:

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

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

    您可以在兩端使用此代碼。 buffer可以是大於零的任何大小。它不需要是文件的大小,並且不會擴展到大文件。

  3. 關閉插座。

如果您需要發送多個文件,或者有一些其他需要保持套接字打開:

  • 發送長度超前的文件,與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,並且您必須調整讀取長度參數以避免超出文件末尾。

  • +0

    評論不適用於擴展討論;這個對話已經[轉移到聊天](http://chat.stackoverflow。COM /間/ 65676 /討論上回答逐EJP-送一個文件,過Java的插座)。 – Flexo 2014-11-26 10:02:05