Tutorial :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?


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.


You can send any Serializable object using something like this.

ByteArrayOutputStream buffer = new ByteArrayOutputStream();  ObjectOutputStream out = new ObjectOutputStream(buffer);  out.writeObject(objectYouWantToSend);  out.close();  buffer.close();  DatagramPacket packet = new       DatagramPacket(buffer.toByteArray(),                      buffer.size(),                      InetAddress.getByName(...),                     portNumber);  socket.send(packet);  


You simply append them before passing them to the network interface. Something along the lines of:

byte[] buff = new byte[256];  // Add al your fields here to buff.  DatagramPacket packet = new DatagramPacket(buff, buff.length, address, 1234);  socket.send(packet);  

If they're not all strings, you'll need to encode them as such.


There are plenty of options for encoding the data, all of which come down to putting the four fields into one data structure, and then sending that all in one go.

The important part is that the encoding needs to show which of the four fields is at which point in the packet, otherwise the far end won't be able to decode it reliably.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »