我有两个类:TcpPacket和IpPacket。 tcpPacket应存储在ip数据包的数据字段中。如何可靠地将tcpPacket对象转换为字节数组,以便将其存储在IpPacket的数据字段中?在收到另一方的数据包后,如何可靠地将其转换回数据包对象?
public static final class TcpPacket {
int source;
int destination;
public Packet( int source, int destination ) {
this.source = source;
this.destination = destination;
}
public String toString() {
return "Source: " + source + ", Dest: " + destination;
}
}
public static final class IpPacket {
byte[] data;
IpPacket( byte[] data ){
this.data = data;
}
}
TcpPacket tcpPacket = new TcpPacket( <someint>, <someint> );
// the following doesn't work because tcppacket is not a byte array.
IpPacket ipPacket = new IpPacket( tcpPacket );
这通常是怎么做的?
谢谢Maricruzz
答案 0 :(得分:1)
这应该可行,只需在从序列化/反序列化函数接收到对象后将其转换为类。
public static byte[] objToByte(TcpPacket tcpPacket) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(byteStream);
objStream.writeObject(tcpPacket);
return byteStream.toByteArray();
}
public static Object byteToObj(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
ObjectInputStream objStream = new ObjectInputStream(byteStream);
return objStream.readObject();
}
答案 1 :(得分:0)
我想为您提供序列化课程的手动方法。
1
添加public static final class TcpPacket {
public byte [] toByteArray() {
ByteBuffer b = ByteBuffer.allocate(4 * 2);
return b.putInt(source).putInt(destination).array();
}
public static TcpPacket fromByteArray(byte [] bytes) {
if (bytes.length < 8) throw new IllegalArgumentException("not enough bytes");
ByteBuffer b = ByteBuffer.wrap(bytes);
int source = b.getInt();
int destination = b.getInt();
return new TcpPacket(source, destination);
}
}
和静态toByteArray
方法可以获得您想要的效果,并具有以下优势:
如果您需要序列化更复杂的数据结构,我强烈建议您选择一个完善的序列化库,例如google protocol buffers(我选择的个人武器)或其他许多不具备的序列库。遭受Java序列化的安全噩梦。