O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading and Writing Serialized Data

Problem

Having connected, you wish to transfer serialized object data.

Solution

Construct an ObjectInputStream or ObjectOutputStream from the socket’s getInputStream( ) or getOutputStream( ).

Discussion

Object serialization is the ability to convert in-memory objects to an external form that can be sent serially (a byte at a time). This is discussed in Section 9.17.

This program (and its server) operate one service that isn’t normally provided by TCP/IP, as it is Java-specific. It looks rather like the DaytimeBinary program in the previous recipe, but the server sends us a Date object already constructed. You can find the server for this program in Section 16.4; Example 15-7 shows the client code.

Example 15-7. DaytimeObject.java

/** * DaytimeObject - connect to the Daytime (ascii) service. */ public class DaytimeObject { /** The TCP port for the object time service. */ public static final short TIME_PORT = 1951; public static void main(String[] argv) { String hostName; if (argv.length == 0) hostName = "localhost"; else hostName = argv[0]; try { Socket sock = new Socket(hostName, TIME_PORT); ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(sock.getInputStream( ))); // Read and validate the Object Object o = is.readObject( ); if (!(o instanceof Date)) throw new IllegalArgumentException("Wanted Date, got " + o); // Valid, so cast to Date, and print Date d = (Date) o; System.out.println("Time on " + hostName + " is " + d.toString( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required