Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

Let's say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuilt from the bytes received.

How could I achieve this?

1 Answer

0 votes
by (46k points)

Design bytes to send:

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutput out = null;

try {

out = new ObjectOutputStream(bos);

out.writeObject(yourObject);

out.flush();

byte[] yourBytes = bos.toByteArray();

...

} finally {

try {

bos.close();

} catch (IOException ex) {

// ignore close exception

}

}

Make object from bytes:

ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);

ObjectInput in = null;

try {

in = new ObjectInputStream(bis);

Object o = in.readObject();

...

} finally {

try {

if (in != null) {

in.close();

}

} catch (IOException ex) {

// ignore close exception

}

}

Related questions

0 votes
1 answer
asked Aug 19, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...