我正在研究一個簡單的應用程序來演示P2P文件傳輸。應用程序獲取文件,並通過數據包大小的數據塊發送。接收器等待這些塊到達。它假設不斷地將傳入的字節數組添加到一個更大的字節數組中,一旦所有字節都到達,該數組稍後將成爲完成的文件。這假設沒有丟包。爲了調試我一直在試圖傳輸一個小的txt文件。我嘗試使用for循環,現在System.arraycopy但packetData的字節數組似乎沒有正確複製到completeFile數組。如何將一個字節數組複製到另一個字節數組中?
public void run() {
try {
byte[] completeFile = new byte[fileSize];//will become the complete file when all bytes have arrived
receivingSocket = new DatagramSocket(49000);
while (bytesReceived<fileSize) {
System.out.println("@@@ Receiver waiting for packet");
byte[] buf = new byte[1500]; // Actual Ethernet packet size is 1500 bytes
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
receivingSocket.receive(packet);
byte[] packetData = Arrays.copyOf(packet.getData(), packet.getLength());
deliverData(packetData);
if(headerReceived && packetsReceived>1)
{
//add incoming bytes to the completeFile
System.arraycopy(packetData, 0, completeFile, bytesReceived, packetData.length);
bytesReceived = bytesReceived + packetData.length;
}
}
FileOutputStream fops = new FileOutputStream("D:\\Desktop\\testing2"+fileExtension);
System.out.println("@@@ BUILDING FILE");
fops.write(completeFile);
fops.close();
} catch (Exception e) {
System.out.println("@@@ SOMETHING WENT WRONG!!!!!!!!!!!!!!");
stopListening();
}
}
「似乎沒有正確地複製到completeFile數組」,它在做什麼呢? – 2015-04-03 23:44:10
當我使用for循環並使用打印語句打印索引時,它只會打印出第一個索引然後崩潰。與system.arraycopy它只是在該行崩潰。 – user3657834 2015-04-04 00:17:10
我通常會推薦使用NIO緩衝區,因爲它們是專門爲這種數據操作而設計的。 – chrylis 2015-04-04 00:30:54