I have two classes: TcpPacket and IpPacket. The tcpPacket should be stored in the data field of the ip packet. How can I reliably convert the tcpPacket object to a byte array so that i can store it in the IpPacket's data field? And upon receiving the packet on the other side, how to reliably convert it back into a packet object?
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 );
How is this usually done?
Thanks Maricruzz
This should work, just cast the object to your class after receiving it from the serialize/deserialize function.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With