gpt4 book ai didi

java - 创建 DatagramPackets 数组时,每个元素都与最近添加的元素相同

转载 作者:行者123 更新时间:2023-12-02 13:19:04 25 4
gpt4 key购买 nike

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 中的每个数组都有一个公共(public) clone() 方法,该方法不会抛出异常:

byte[] sendData = buffer.array().clone();

关于java - 创建 DatagramPackets 数组时,每个元素都与最近添加的元素相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com