O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

In the previous chapter, you saw a program that read a Date object over an ObjectInputStream. This code is the other end of that process, the DaytimeObjectServer . Example 16-5 is a server that constructs a Date object each time it’s connected to, and returns it.

Example 16-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);
        }
    }
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required