通过UDP解码java中的C结构数据包



这是我的Android应用程序的java代码:

InetAddress address = InetAddress.getByName("192.168.x.xxx");
int port = xxx;
DatagramPacket p = new DatagramPacket(buffer, buffer.length, address, port);
DatagramSocket ds = new DatagramSocket(port);
ds.receive(p);
Log.d("..........","Packet Received");
Log.d("UDP", "Received: '" + new String(p.getData()).trim() + "'");

我能够接收数据包,但我不能以正确的方式解码。另一方面,我在结构(C程序)中发送数据包。我没有权利改变服务器代码,所以我需要解码服务器结构包成java对象??

使用ByteBuffer从p.getData()获得byte[]。然后使用ByteBuffer的getXXX方法来检索相应的值。

对于第一个char"frameType"的例子,你可以这样做:

char frameType = (char) myByteBuffer.get(); // getChar() would fetch 2 bytes !!

最新更新