2012-05-20 58 views
0

我試圖創建一個TFTP服務器,但當它收到一個文件似乎並不是所有的都保存到服務器上(有些字節丟失)。該文件創建正常,大部分數據被寫入,但由於文件不完整,它被歸類爲腐敗和無法打開。有誰知道如何解決這個問題?BufferedOutputStream不寫入所有文件

主類

  WRQ WRQ = new WRQ(); 
      ACK ACK = new ACK(); 
      DatagramPacket outPacket; 
      BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename)); 
      byte[] bytes; 
      byte[] fileOut; 
      outPacket = WRQ.firstPacket(packet); 
      socket.send(outPacket); 

      socket.receive(packet); 

      while (packet.getLength() == 516){ 

      bytes = WRQ.doWRQ(packet); 
      bufferedOutput.write(bytes); 

      outPacket = ACK.doACK(packet); 
      socket.send(outPacket); 

      socket.receive(packet); 

      } 

      bytes = WRQ.doWRQ(packet); 
      bufferedOutput.write(bytes); 

      bufferedOutput.close(); 

      outPacket = ACK.doACK(packet); 
      socket.send(outPacket); 

WRQ類

public class WRQ { 

public DatagramPacket firstPacket(DatagramPacket packet) throws IOException{ 

    ACK ACK = new ACK(); 
    DatagramPacket ACKpacket = ACK.doACK(packet); 

    //takes ACK packet and sets block # as 0 to signal that this is the first packet in a WRQ 
    byte[] ACKcontents = new byte[3]; 
    ACKcontents = ACKpacket.getData(); 
    ACKcontents[2] = 0; 
    ACKcontents[3] = 0; 
    ACKpacket.setData(ACKcontents); 

    return ACKpacket; 

} 

public byte[] doWRQ(DatagramPacket packet){ 

    int length = packet.getLength(); 
    byte[] packetData = packet.getData(); 
    byte[] data = new byte[length - 4]; 
    data = Arrays.copyOfRange(packetData, 4, length - 4); 

    return data; 

} 

} 
+0

您可以編輯您的上一個問題。 –

+0

感謝您的幫助。下次我會記住這一點。你能幫助解決這個問題嗎? – DMo

+1

問題可能出在您沒有向我們顯示的代碼中。例如WRQ.doWRQ()方法。嘗試記錄在客戶端上發送的字節,並寫入服務器上的文件,並對它們進行比較。 –

回答

1

這個代碼看起來非常可疑對我說:

byte[] packetData = packet.getData(); 
byte[] data = new byte[length - 4]; 
data = Arrays.copyOfRange(packetData, 4, length - 4); 

你的輸出數組(數據)的長度爲length - 4,但你只複製length - 8字節。如果在分組數據忽略字節是第一個4個字節,它應該是

data = Arrays.copyOfRange(packetData, 4, length); 

因爲最後一個參數是不是一個長度,但to索引(不包括)。詳情請見the javadoc

+0

謝謝,我只是想到了這一點,但事實上這是問題所在。我在想這是一個長度的爭論。 – DMo