package example9_3_RemoteProxy.client; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import example9_3_RemoteProxy.dateService.DateService; import example9_3_RemoteProxy.dateService.Message; // This class implements a remote proxy to a "real" DateService-implemented object public class DateProxy implements DateService { private Socket socket; // this client's socket private InetAddress netAddr; private ObjectInputStream fromServerStream; // for reading from server private DataOutputStream toServerStream; // for writing to server /** * Constructor */ public DateProxy() throws Exception { // Create and connect a client-side socket to a pre-existing server socket // localhost is 127.0.0.1 byte[] addr = {(byte)127,(byte)0,(byte)0, (byte)1}; // 127.0.0.1 is the local loopback IP address // Create the socket connection try{ netAddr = InetAddress.getByAddress(addr); System.out.println("Connecting to server..."); socket = new Socket(netAddr, 80); // connect to server at this IP address on the specified port System.out.println("Connected to server; starting to send and receive..."); toServerStream = new DataOutputStream(socket.getOutputStream()); fromServerStream = new ObjectInputStream(socket.getInputStream()); } catch( UnknownHostException e ) { throw new Exception("Unknown host"); } catch( IOException e ) { throw new Exception("Can't connect to server-side socket."); } } /** * Form a request to return the current date from the server * @return the current date as a String */ @Override public String getDate() { String retVal; try { toServerStream.writeInt(Message.DATEREQUEST); Message response = (Message)fromServerStream.readObject(); retVal = response.getValue(); } catch( ClassNotFoundException e ) { retVal = "proxy class cast error; possible JDK incompatibility"; } catch( IOException e ) { retVal = "proxy read error."; } return retVal; } /** * Serialize a request to return the current time from the server * @return the current time in ms (after 1/1/1970) as a String */ @Override public String getTime() { String retVal; try { toServerStream.writeInt(Message.TIMEREQUEST); Message response = (Message)fromServerStream.readObject(); retVal = response.getValue(); } catch( ClassNotFoundException e ) { retVal = "proxy class cast error; possible JDK incompatibility"; } catch( IOException e ) { retVal = "proxy read error."; } return retVal; } }