Returning an Object


Socket clientSock = serverSocket.accept(); ObjectOutputStream os = new ObjectOutputStream(     clientSock.getOutputStream( )); // return an object os.writeObject(new Date()); os.close();



In this phrase, we return a serialized object to a client. We get a Socket instance returned from the accept() method of the ServerSocket after making a connection with a client. We then create an ObjectOutputStream instance, passing the output stream obtained from the client socket. An ObjectOutputStream is used to write primitive datatypes and graphs of Java objects to an OutputStream. In this example, we write a Date object to the output stream and then close the stream.

The writeObject() method causes the object passed as a parameter to be serialized. In this phrase, this is a Date object. All data fields that are non-transient and non-static will be preserved in the serialization and restored when the object is deserialized. Only objects that support the java.io.Serializable interface can be serialized.

An interesting alternative to the ObjectOutputStream and ObjectInputStream classes is an open source project from codehaus.org called XStream. XStream provides alternative implementations of ObjectInputStream and ObjectOutputStream, enabling streams of objects to be serialized or deserialized from XML. The standard ObjectInputStream class uses a binary format for the serialized data. The serialized output of the XStream classes provides the serialized classes in easy-to-read XML format. You can find more information about XStream and download it from: http://xstream.codehaus.org/index.html




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net