Recipe 17.3 Returning Object Information


Problem

You need to return an object.

Solution

Create the object you need, and write it using an ObjectOutputStream created on top of the socket's output stream.

Discussion

The program in Example 16-7 in the previous chapter reads a Date object over an ObjectInputStream. Example 17-5, the DaytimeObjectServer the other end of that process is a program that constructs a Date object each time it's connected to and returns it to the client.

Example 17-5. DaytimeObjectServer.java
/*  */ public class DaytimeObjectServer {     /** The TCP port for the object time service. */     public static final short TIME_PORT = 1951;     public static void main(String[] argv) {         ServerSocket sock;         Socket  clientSock;         try {             sock = new ServerSocket(TIME_PORT);             while ((clientSock = sock.accept(  )) != null) {                 System.out.println("Accept from " +                      clientSock.getInetAddress(  ));                 ObjectOutputStream os = new ObjectOutputStream(                     clientSock.getOutputStream(  ));                 // Construct and write the Object                 os.writeObject(new Date(  ));                 os.close(  );             }         } catch (IOException e) {             System.err.println(e);         }     } }



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