ProblemHaving connected, you wish to transfer serialized object data. SolutionConstruct an ObjectInputStream or ObjectOutputStream from the socket's getInputStream( ) or getOutputStream( ). DiscussionObject 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> |