我有一个类Packet,我编写了该类以填充516个字节的byte[]数组。 packetNumshort)为2,authKeyshort)为2,audiobyte[])为512。在我的Packet类内部是一种方法,将这些属性组合在一起以创建大小为516的byte[]数组,以发送给接收者:

public byte[] toByteArray() {
    byte[] fullArray = new byte[516];

    ByteBuffer packetNumBuffer = ByteBuffer.allocate(2);
    packetNumBuffer.putShort(this.packetNum);
    byte[] packetNumArray = packetNumBuffer.array();

    ByteBuffer authKeyBuffer = ByteBuffer.allocate(2);
    authKeyBuffer.putShort(this.authKey);
    byte[] authKeyArray = authKeyBuffer.array();

    System.arraycopy(packetNumArray, 0, fullArray, 0, packetNumArray.length);
    System.arraycopy(authKeyArray, 0, fullArray, packetNumArray.length, authKeyArray.length);
    System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);
    return fullArray;
}


现在,当测试接收到的数据包时,我的packetNum(在创建下一个Packet之前递增)已成功传输-但是,authKeyaudio完全错误。这是我的代码的输出,它使用Packetshort authKey = 10创建一个新的short packetNum = 0

Packet number: 0
Auth key = -7936
Packet number: 1
Auth key = 19201
Packet number: 2
Auth key = 31490
Packet number: 3
Auth key = -1
Packet number: 4
Auth key = -2
Packet number: 5
Auth key = -3
Packet number: 6
Auth key = -4
Packet number: 7
Auth key = -3
Packet number: 8
Auth key = -2
Packet number: 9
Auth key = -1
Packet number: 10
Auth key = 8192


auth密钥会为每个数据包吐出随机数,而所有数据包均应为10。这使我相信我的方法没有按预期填充fullArray。谁能发现我做错了什么?

最佳答案

错误就在这里

System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);


起始位置是authKeyArray.length
但这应该是authKeyArray.length + packetNumArray.length



无论如何,System.arraycopy是绝对要避免的那些方法之一。
我的建议是,使用ByteArrayOutputStream

final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(516);
outputStream.write(packetNumArray);
outputStream.write(authKeyArray);
outputStream.write(audio);
final byte[] fullArray = outputStream.toByteArray();


它不是更优雅吗?

10-06 16:01