manas
manas

Reputation: 31

How to send Object over Datagram Socket

I am working on some Android Project & trying to pass object over Datagram Socket to some another device Object contains 'String' Data Members of the class ( UserName,Services) .. How can I do that??

Upvotes: 3

Views: 7985

Answers (2)

Ahmed Adm
Ahmed Adm

Reputation: 31

Object transport via datagram packets

you can not send object via nework as object , you have to convert it to array of bytes by using this classes

  • ObjectOutputStream
  • ByteArrayOutputStream

and then send it via DatagramPacket class, but your own class should be serializable by adding implementing serializable interface if you look to the link above you will get more details step by step and more helpful

Upvotes: 0

Perception
Perception

Reputation: 80603

Layer an ObjectOutputStream on top of a ByteArrayOutputStream on the sending side. Gather the bytes from the ByteArrayOutputStream (after the write), and send that in your datagram packet. Do the reverse on the receiving side to unpack the data back into an Object.

Pseudocode for your sending side:

final ByteArrayOutputStream baos = new ByteArrayOutputStream(6400);
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
final byte[] data = baos.toByteArray();

final DatagramPacket packet = new DatagramPacket(data, data.length);
// Send the packet

Upvotes: 8

Related Questions