// // example of use of java.net.* classes and serialization: // set up client/server interaction in which client sends request // object to server for processing and server returns result. // this file defines classes for request objects; RequestServer.java // and RequestClient.java contain the programs for the server and // client. // example adapted from one in chapter 11 of _Exploring Java_ by // Niemeyer & Peck. // // // the Request class is the base class for requests to be sent from // the client to the server. // implement Serializable so our objects can be serialized for // transmission over the network. // abstract class Request implements java.io.Serializable { // subclasses implement this method to define what service // they want the server to perform. return type is // Object to permit returning any type. abstract public Object serviceRequest() ; // subclasses can override this method. public String toString() { return "Request" ; } } // // a ShowLocalTime object represents a request that the server // create and format a Date object showing the local time/date // at the server. what is returned is a string showing // local time/date. // class ShowLocalTime extends Request { public Object serviceRequest() { System.out.println("servicing ShowLocalTime") ; return new java.util.Date().toString() ; } public String toString() { return "ShowLocalTime" ; } } // // a FindRealRoots object represents a request that the server // calculate the real roots of the quadratic equation // a*x*x + b*x + c = 0. what is returned is an array // containing the 0, 1, or 2 real roots. // since such a request must include some data (values for // a, b, and c), we define some instance variables // and provide an appropriate constructor. // class FindRealRoots extends Request { double a, b, c ; FindRealRoots(double a, double b, double c) { this.a = a ; this.b = b ; this.c = c ; } public Object serviceRequest() { System.out.println("servicing FindRealRoots") ; double discrim = b*b - 4*a*c ; double[] roots ; if (discrim < 0) { roots = new double[0] ; } else if (discrim == 0) { roots = new double[1] ; roots[0] = (-b)/(2*a) ; } else { roots = new double[2] ; roots[0] = (-b + Math.sqrt(discrim))/(2*a) ; roots[1] = (-b - Math.sqrt(discrim))/(2*a) ; } return roots ; } public String toString() { return "FindRealRoots (" + a + ", " + b + ", " + c + ")" ; } }