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??
Asked
Active
Viewed 7,616 times
3
-
Although I learned about some concept of converting object to bytes .. but while debugging I found , bytes recived is not getting converted into Object again .. Although Bytes are being received properly... – manas Apr 27 '12 at 23:02
-
You will have to construct a new object on the receiving end from the constituent members. If some of those are not trivially serializable objects, you'll have to construct those first from components which are. Ie, you feed all the necessary constructors with the data you got from the socket. – Chris Stratton Apr 27 '12 at 23:15
-
@user1362127 UDP is unreliable and some packets just don't reach their target & some might get delayed and come late. If you want to transfer Strings and other objects and don't want to retransmit & reorder packets you should use TCP Sockets. -> http://stackoverflow.com/questions/6531956/java-reliable-udp – zapl Apr 28 '12 at 00:04
2 Answers
8
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

Perception
- 79,279
- 19
- 185
- 195
0
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

Ahmed Adm
- 31
- 6
-
-
-
1you 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 – Ahmed Adm Dec 03 '14 at 12:22
-
please give this detail in your answer by editing it. and welcome to Stack Overflow and thanks for the answer! – Syeda Zunaira Dec 03 '14 at 12:28