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( ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.