Recipe 16.6 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 Recipe 10.18.

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 Recipe 17.2; Example 16-7 shows the client code.

Example 16-7. DaytimeObject.java
/**  * DaytimeObject - connect to the non-standard Time (object)  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( ));         } catch (ClassNotFoundException e) {             System.err.println("Wanted date, got INVALID CLASS (" + e + ")");         } catch (IOException e) {             System.err.println(e);         }     } }

I ask the operating system for the date and time, and then run the program, which prints the date and time on a remote machine.

C:\javasrc\network>date /t Current date is Sun 01-23-2000  C:\javasrc\network>time /t Current time is  2:52:35.43p  C:\javasrc\network>java DaytimeObject aragorn  Time on aragorn is Sun Jan 23 14:52:25 GMT 2000 C:\javasrc\network>



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

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