javaudppackets

Send multiple data in 1 single UDP datagram


i'm working on a network programming assignment about writing a simple IM system (pretty much like the simplest version of windows messenger).

the spec specifies that i must send over 4 fields of data in a single datagram packet, those are:

To From Type Message
where type refers to message type, implemented as a user defined enum class.

I would like to be taught how to pack all these datas into a single packet.

UPDATE: thx for the help so far, but say i have String sentence and String From the normal way to patch the packet individually would be

byte[] sendData = new byte [256]
sendData = sentence.getBytes();

but how exactly can i append the "from" string to sendData along with the sentence string?


Solution

  • Briefly, what you need to do is:

    1. create an object (class) which contains your 4 fields (from/to/enum/message)
    2. serialise this. It has to implement Serializable. See other solutions here for how to serialise
    3. convert to a byte array and send down the socket (see elsewhere for details)

    At the other end you'll read this bytestream, deserialise and cast it to an instance of your class defined in 1. above.

    By creating the one object containing the 4 fields and serialising this object, this allows you to send all four fields together (I get the impression that this is the stumbling block?).

    Note that datagrams will have size limits imposed by the network transport layers, but for this application I suspect that's not a problem.