简体   繁体   中英

How to send Object over Datagram Socket

我正在某个Android项目上进行尝试,并尝试通过Datagram Socket将对象传递给其他设备。对象包含类的“字符串”数据成员(UserName,Services)..我该怎么做?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM