簡體   English   中英

Java讀取文件並通過DatagramSocket發送

[英]Java reading a file and sending it via DatagramSocket

使用Java,我試圖通過DatagramSocket發送一些文件數據。 我需要讀取1000字節的文件塊並將其作為數據包發送出去。 我的代碼:

  1. 將文件讀取到包裝在字節緩沖區中的字節數組中
  2. 將數據放在數據包中並發送
  3. 讓接收者打開數據包並將內容重新寫入新文件。

我在將字節數組寫回到文件時遇到問題。 請在下面查看我的代碼。

客戶端/發件人:

byte[] data = new byte[1000];
ByteBuffer b = ByteBuffer.wrap(data);
DatagramPacket pkt;
File file = new File(sourceFile);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
CRC32 crc = new CRC32();

while(true){
    b.clear();
    b.putLong(0); // I need to put the checksum at the beginning for easy retrieval
    bytesRead = bis.read(data);
    if(bytesRead==-1) { break; }
    crc.reset();
    crc.update(data, 8, data.length-8);
    long chksum = crc.getValue();
    b.rewind();
    b.putLong(chksum);
    pkt = new DatagramPacket(data, 1000, addr); // addr is valid, works fine
    sk.send(pkt);
}

bis.close();
fis.close();

服務器/接收器:

DatagramSocket sk = new DatagramSocket(port);

File destfile = new File("hello.txt");
FileOutputStream fos = new FileOutputStream(destfile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintStream ps = new PrintStream(fos);

byte[] data = new byte[1000];
DatagramPacket pkt = new DatagramPacket(data, data.length);
ByteBuffer b = ByteBuffer.wrap(data);
CRC32 crc = new CRC32();

while(true) {
    pkt.setLength(data.length);
    sk.receive(pkt);
    b.rewind();

    // compare checksum, print error if checksum is different
    // if checksum is the same:
    bos.write(data);  // Where the problem seems to be occurring.

    // send acknowledgement packet. 
}
bos.close();
fos.close();

在這里,我主要遇到寫回文件的問題。 帶有一個小的文本文件,上面寫着“ Hello World! ,我得到一個奇怪的輸出,說vˇ]rld! 同樣,輸入文件只有12個字節,但是接收者創建的文件是1KB。

我認為我的問題是處理字節緩沖區-我編寫了一個程序,該程序使用文件流和緩沖流復制文件,效果很好。 但是我對流在這種情況下的工作方式感到困惑,我將非常感謝您的幫助。 謝謝!

在發件人的data []中,您將覆蓋crc從文件中讀取的文本! 您必須閱讀很長一段時間后的內容。 在發件人中更正此錯誤時,它的工作原理是:

//int bytesRead = bis.read(data); --old code
int bytesRead=bis.read(data,8,data.length-8);

此外,您發送1000字節,因此將接收1000字節,該字節將進入destfile。

順便說一句:您不檢查服務器中的crc。...為什么要發送它?

暫無
暫無

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

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