I am supposed to create my own 'reliable transport protocol' using UDP and written in java. Not too terribly difficult, however, to make it a more organized implementation, I was hoping on creating my own version of the DatagramPacket class by extension, adding some byte headers to be read upon receipt from remote host, and pass this new type of packet through a regular DatagramSocket via typecast, or perhaps extend the DatagramSocket class as well to implement more methods. Turns out the DatagramPacket class is final, and I'm too stubborn to give up on my idea. Anyone know any ways around this to achieve the ability to send such a custom packet type? Thanks in advance!
2
votes
1 Answers
2
votes
Subclassing to provide alternate behavior is one way, but it's not always feasible as you've noticed. Can you somehow come up with a solution based on composition rather than inheritance?
See if you can make it work by having your class have-a
DatagramPacket
as a member variable, enhancing its behavior by wrapping your class's methods around the DatagramPacket
's.
It sounds like you want to still send DatagramPackets in the end, but with some special processing in addition to what DatagramSocket already does. Here's a design that comes to mind (I'm sure there are many others):
class JayPacket {
private byte[] payload; // Payload without any flow control bytes
// Other flow control magic
public DatagramPacket asDatagramPacket() {
// Package this instance's payload plus your flow control bytes
// into a DatagramPacket
}
public static JayPacket fromDatagramPacket(DatagramPacket datagramPacket) {
// Parse the control bytes out of the given DatagramPacket
// and construct a JayPacket
}
}
Then another class would wrap around DatagramSocket
to manage JayPacket <--> DatagramPacket
conversions.