2012-04-14 66 views
1

我有一種情況,服務器首先發送文件大小和文件數據。在客戶端讀取時如何區分整數值和文件數據?服務器區分TCP中的數據包IP

Sameple代碼(OS是的BufferedOutputStream):

  // Construct a 1K buffer to hold bytes on their way to the socket. 
      byte[] mybytearray = new byte[(int) myFile.length()]; 

      //File Size 
      os.write((int) myFile.length()); 

    FileInputStream fis = null; 
    System.out.println("test+sendbytes"); 
    // Copy requested file into the socket's output stream. 
     try { 
      fis = new FileInputStream(myFile); 
     } catch (FileNotFoundException ex) { 
      // Do exception handling 
     } 
     BufferedInputStream bis = new BufferedInputStream(fis); 

     try { 
      bis.read(mybytearray, 0, mybytearray.length); 
      os.write(mybytearray, 0, mybytearray.length); 
      os.flush(); 
      os.close(); 
      os.close(); 

      // File sent, exit the main method 
      return; 
     } catch (IOException ex) { 
      // Do exception handling 
     } 
+0

正如Peter Lawrey的答案中指出的那樣,'os.write((int)myFile.length())'*錯誤*。它使用值myFile.length()&0xFF'寫入一個字節。另外,在os.close()之前調用'os.flush()'是不必要的。 'close()'總是刷新任何核心IO類中的剩餘數據。 – 2012-04-14 12:04:28

回答

1

你需要寫長度爲int除非你是假設所有文件arfe不超過255個字節。嘗試DataOutputStream.writeInt()

對於閱讀你必須承擔一個訂單。即你假設長度先發送,然後是內容。使用DataInputStream.readInt()來讀取長度。

+0

謝謝彼得。我發送的文件大小爲4mb。所以當我將Datainputstream.readInt()讀入一個變量時,它會將它存儲到該變量中嗎? – DesperateLearner 2012-04-14 10:26:00

+0

是的,一個'int'字段,其長度可以讀取。您可以一次讀取部分數據來減少此數據。 – 2012-04-14 10:28:18