Java Reference
In-Depth Information
Solution
Construct an ObjectInputStream or ObjectOutputStream from the socket's getIn-
putStream() 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 Saving and Restoring Java Objects .
This program (and its server) operate one service that isn't normally provided by TCP/IP, be-
cause it is Java-specific. It looks rather like the DaytimeBinary program in the previous re-
cipe, but the server sends us a Date object already constructed. You can find the server for
this program in Returning a Response (String or Binary) ; Example 13-7 shows the client
code.
Example 13-7. DaytimeObject.java
public
public class
DaytimeObject {
/** The TCP port for the object time service. */
public
class DaytimeObject
public static
static final
final short
short TIME_PORT = 1951 ;
public
public static
void main ( String [] argv ) {
String hostName ;
iif ( argv . length == 0 )
hostName = "localhost" ;
static void
else
else
hostName = argv [ 0 ];
try
try {
Socket sock = new
new Socket ( hostName , TIME_PORT );
ObjectInputStream is = new
new
BufferedInputStream ( sock . getInputStream ()));
new ObjectInputStream ( new
// Read and validate the Object
Object o = is . readObject ();
iif ( o == null
null ) {
System . err . println ( "Read null from server!" );
} else
else iif (( o instanceof
instanceof Date )) {
// Valid, so cast to Date, and print
Date d = ( Date ) o ;
System . out . println ( "Server host is " + hostName );
System . out . println ( "Time there is " + d . toString ());
Search WWH ::




Custom Search