Back
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?
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}}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
out.flush();
byte[] yourBytes = bos.toByteArray();
...
} finally {
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}}
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
in = new ObjectInputStream(bis);
Object o = in.readObject();
if (in != null) {
in.close();
31k questions
32.8k answers
501 comments
693 users