Home >Java >javaTutorial >How Can I Serialize and Deserialize Java Objects for Socket Communication?
Problem:
Consider a scenario where a serializable class called AppMessage needs to be transmitted over sockets to another machine and rebuilt from the received bytes. The objective is to explore techniques for achieving this objective in Java.
Solution:
To prepare the byte array for transmission, utilize the serialize method:
static byte[] serialize(final Object obj) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(bos)) { out.writeObject(obj); out.flush(); return bos.toByteArray(); } catch (Exception ex) { throw new RuntimeException(ex); } }
Conversely, to recreate an object from a byte array, employ the deserialize method:
static Object deserialize(byte[] bytes) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); try (ObjectInput in = new ObjectInputStream(bis)) { return in.readObject(); } catch (Exception ex) { throw new RuntimeException(ex); } }
These methods enable efficient serialization and deserialization of Java objects, facilitating their transmission over sockets for reconstruction on the receiving machine.
The above is the detailed content of How Can I Serialize and Deserialize Java Objects for Socket Communication?. For more information, please follow other related articles on the PHP Chinese website!