我是Java的新手,通过UDP / TCP编写自己的网络协议程序。 C中有这样一个包:
struct test_package {
u32 cmd;
u32 args;
u32 flags;
};
以UDP为例,我从DatagramPacket得到的是字节数据[]。如何将其转换为包结构?
如果在C中,如果没有对齐限制则只有(struct test_package *)data
。
由于
答案 0 :(得分:1)
假设你有一个班级:
public class TestPackage implements Serializable
{
long cmd;
long args;
long flags;
}
您可以通过序列化将其作为byte []存储在DatagramPacket中。然后在另一端,你可以取byte []并将其反序列化回TestPackage的确切实例。
(这是序列化/反序列化的样子)
public static byte[] serialize(Object object) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(object);
return out.toByteArray();
}
public static Object deserialize(byte[] datagramData) {
ByteArrayInputStream in = new ByteArrayInputStream(datagramData);
ObjectInputStream ois = new ObjectInputStream(in);
return ois.readObject();
}
答案 1 :(得分:0)
Java不提供直接内存访问,因此您无法像在C中那样将其强制转换为结构。您必须自己解析字节数组,例如:
byte data[] = ...;
DataInput input = new DataInputStream(new ByteArrayInputStream(data));
int cmd = input.readInt();
int args = input.readInt();
int flags = input.readInt();