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!
Asked
Active
Viewed 560 times
1 Answers
2
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.
-
I thought this would work at first, but I don't think it will. The DatagramSocket class's method 'send' only takes a DatagramPacket as a parameter. I'm starting to think it may be easier just to include chars in the payload and parse the data upon receipt.. Any pros/cons come to mind? – Jay Elrod Mar 19 '12 at 07:34
-
I added an example in my design along those lines, see if it helps! – oksayt Mar 19 '12 at 07:50
-
Ah, I see what you mean. I think it may be the same amount of work to do either way. I will play around with it. Thanks a lot! – Jay Elrod Mar 19 '12 at 07:55
-
@JayElrod, strictly speaking, if your `NewDatagramSocket.send` does not accept the "traditional" `DatagramPacket` as `DatagramSocket` does, then `NewDatagramSocket` *is not* a `DatagramSocket`. Just create your own "socket" class. :) – wks Mar 19 '12 at 08:03
-
@wks, how can you create a socket class that sends packets in the same fashion? I need this protocol to be UDP-like in the least, without any established connection. – Jay Elrod Mar 19 '12 at 08:18