public DatagramPacket[] makePackets(byte[] data, InetAddress IP, int portNumber) {
// create packet buffer
ByteBuffer buffer = ByteBuffer.allocate(packetSize);
// calculate number of packets
int dataSize = packetSize - 10;
int totalPackets = data.length / dataSize;
if(data.length % dataSize > 0)
totalPackets++;
System.out.println("Total Packets " + totalPackets);
DatagramPacket[] pkts = new DatagramPacket[totalPackets];
for(int seqNumber = 0; seqNumber < totalPackets; seqNumber++)
{
// insert metadata
buffer.putChar(informUpdate);
buffer.putInt(seqNumber);
buffer.putInt(totalPackets);
// adds data to the buffer
if(seqNumber == totalPackets -1) // if last packet adjust length to avoid null pointer
buffer.put(data, seqNumber * dataSize, data.length - seqNumber*dataSize);
else
buffer.put(data, seqNumber * dataSize, dataSize);
// create packet
byte[] sendData = buffer.array();
// add packets to packet array and clear buffer
pkts[seqNumber] = new DatagramPacket(sendData, sendData.length, IP, portNumber);
System.out.println(new String(pkts[seqNumber].getData())); // <- Check if packets are being made correctly
buffer.clear();
}
// this shows prints all elements in pkts which proves all data is the same
for(int i = 0; i < pkts.length; i++)
System.out.println(new String(pkts[i].getData()));
return pkts; }
希望我以可读格式添加了代码。提前谢谢!
最佳答案
执行此操作时:
byte[] sendData = buffer.array();
您在每次循环迭代中都检索相同的字节数组。您创建的每个DatagramPacket都在重复使用相同的字节数组。
最简单的解决方案是克隆字节数组,因为Java中的每个数组都有一个公共的
clone()
方法,该方法不会引发任何异常:byte[] sendData = buffer.array().clone();