Construct an
ObjectInputStream
or ObjectOutputStream
from the socket’s getInputStream( )
or
getOutputStream( )
.
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( )); } 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. The server and my desktop are within about ten seconds of agreement:
C:javasrc etwork>date Current date is Sun 01-23-2000 Enter new date (mm-dd-yy): C:javasrc etwork>time Current time is 2:52:35.43p Enter new time: C:javasrc etwork>java DaytimeObject Time on localhost is Sun Jan 23 14:52:25 GMT 2000 C:javasrc etwork>
3.16.76.138