我正在开发一个简单的应用程序来演示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();
}
}
答案 0 :(得分:0)
你不需要复制任何东西。您可以直接从用于构造DatagramPacket,
的字节数组中直接写入文件,并且您可以将该字节数组直接传递给其他方法,当然也可以将数据包的长度传递给其他方法。 / p>