views:

979

answers:

3

Just want to know if there's a tutorial or an how-to for serializing object, put it in a stream over network, and deserialize it on the other point. I understand the principles of serialization, I/O, streams, sockets and so on, just want an example (client sending object to a server) to start with.

Thank you.

+5  A: 

Its pretty simple, actually. Just make your objects serializable, and create an ObjectOutputStream and ObjectInputStream that are connected to whatever underlying stream you have, say FileInputStream, etc. Then just write() whatever object you want to the stream and read it on the other side.

Heres an example for you.

John Ellinwood
You might want to be a little more careful about closing your resources than that example.
Tom Hawtin - tackline
+4  A: 

Java provides (binary) object serialization using the ObjectOutputStream (and ObjectInputStream). You can just writeObject() into the stream and readObject() on the other end. All you need to do for this to work is implement the Serializable interface.

But rather than doing that manually, you may be interested in taken it one level up and using Remote Method Invocation. With RMI you can call methods on objects that live in another JVM, and all the serialization and networking happens under the hood.

And for the sake of completeness, there is also XML bean serialization, if you cannot use the binary format. That XML format is very generic (read: verbose and ugly), but there are some popular libraries (like XStream) that create alternative XML serializations.

Thilo
XStream also offers JSON serialization (with Jettison) which can be very useful in cross-language projects: www.json.org
mjustin
Never heard about RMI, seems like WCF in Microsoft technology, hope I'm not wrong... Thank you for the idea !
elbaid
+1  A: 

This (pdf) is a useful tutorial which walks you through the basics of serialisation, and sockets, then ties the two concepts together (about halfway through the slides) to show how to serialise an object and send it from client to server (no RMI). I think that's precisely what you want.

Brian Agnew
Really show how to use serialization AND sockets, thank you !
elbaid