我正在为字节数组创建一个类对象,请参见此处,并通过 UDP 通信将此数组传递DatagramPacket
到目的地发送。在目标端,有 C 应用程序正在运行,我得到了有线字符。我该死的肯定这与字节顺序有关。因为我能够在接收数据包时将 C 的结构转换为类,但反之亦然。以下是 sudo - 代码:
// recieving part
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet)
UdpPacket udp = new UdpPacket(buffer);
class UdpPacket implements Serializable
{
int a;
byte []message = new byte[10];
public UdpPacket(byte[] data)
{
ByteBuffer bb = ByteBuffer.wrap(data);
bb.order(ByteOrder.nativeOrder());
a = bb.getInt();
bb.get(message);
}
}
// sending ..
根据上述链接将 UdpPacket 对象转换为字节数组,但在目的地总是有垃圾值
DatagramSocket clientSocket = new DatagramSocket();
byte [] respoBytes = ObjectSerializer.serializeObject(udpPacket);
ByteBuffer bb = ByteBuffer.wrap(respoBytes);
byte []test = new byte[1116];
bb.order(ByteOrder.nativeOrder()); // tried all the orders here
bb.get(test);
DatagramPacket sendPacket = new DatagramPacket(test,test.length,client, Integer.parseInt(TxtFdPort.getText().toString()));
clientSocket.send(sendPacket)
;