Assignment two: WomenMarket

Let's create a simple Java RMI example together!
Objectives:  Get an idea of distributed object communication

 

WomenMarketServer.java

 

View Code
  1  /*
  2   * To change this template, choose Tools | Templates
  3   * and open the template in the editor.
  4    */
  5  package womenmarket;
  6 
  7  import java.rmi.Naming;
  8  import java.rmi.RemoteException;
  9  import java.rmi.registry.LocateRegistry;
 10  import java.rmi.server.UnicastRemoteObject;
 11  import java.util.Hashtable;
 12 
 13  /**
 14   * 20120413
 15   *  @author  iltaek
 16    */
 17  public  class WomenMarketServer  extends UnicastRemoteObject  implements WomenMarketInterface {
 18 
 19     Hashtable<String, Double> WomenTable =  new Hashtable<String, Double> ();
 20     
 21      public WomenMarketServer()  throws RemoteException{
 22          super();
 23     }
 24     
 25      public  static  void main(String[] args) {
 26        //  TODO code application logic here
 27           try {
 28              //  Define name of the server which will appear in the
 29               //  RMI Registry lookup service.
 30              String serverName = "WomenMarket";
 31 
 32              //  get port from input parameter or use the default
 33               int port = 1099;
 34              if(args.length == 1) {
 35                  try {
 36                     port = Integer.parseInt(args[0]);
 37                 }  catch(NumberFormatException nfe) {
 38                     System.out.println("Port parameter should be an integer. Using default 1199.");
 39                 }
 40             }
 41             
 42              //  create an instance of HelloServer and bind
 43               //  it to the RMI Registry.
 44              WomenMarketInterface server =  new WomenMarketServer();    
 45             LocateRegistry.createRegistry(port);
 46             Naming.rebind("rmi://127.0.0.1:"+port+"/"+serverName, server);
 47             System.out.println("WomenMarketServer bound");
 48         }  catch (Exception e) {
 49             System.err.println("WomenMarketServer exception:");
 50             e.printStackTrace();
 51         }
 52     }
 53 
 54     @Override
 55      public  boolean addWomen(String name,  double Weight)  throws RemoteException {
 56     
 57          try {
 58              if(!WomenTable.containsKey(name)){
 59                 WomenTable.put(name, Weight);
 60                  return  true;
 61             }
 62              else{
 63                  return  false;
 64             }
 65         }
 66          catch (Exception e) {
 67              return  false;
 68         }
 69         
 70     }
 71 
 72     @Override
 73      public  boolean removeWomen(String name)  throws RemoteException {
 74     
 75          try {
 76              if(WomenTable.containsKey(name)){
 77                 WomenTable.remove(name);
 78                  return  true;
 79             }
 80              else{
 81                  return  false;
 82             }
 83         }
 84          catch (Exception e) {
 85              return  false;
 86         }
 87         
 88     }
 89 
 90     @Override
 91      public  boolean updateWomen(String name,  double newWeight)  throws RemoteException {
 92     
 93          try {
 94              if(WomenTable.containsKey(name)){
 95                 WomenTable.put(name, newWeight);
 96                  return  true;
 97             }
 98              else{
 99                  return  false;
100             }
101         }
102          catch (Exception e) {
103              return  false;
104         }
105         
106     }
107 
108     @Override
109      public  double getWomen(String name)  throws RemoteException {
110     
111          try {
112              // if(WomenTable.containsKey(name)){
113                   return (Double) WomenTable.get(name);
114             //  }
115 
116         }
117          catch (Exception e) {
118              return -1;
119         }
120         
121     }
122 
123     @Override
124      public Hashtable getAllWomen()  throws RemoteException {
125     
126          try {
127                  return WomenTable;
128             }
129      
130          catch (Exception e) {
131              return  null;
132         }
133         
134     }
135 }

 

 

WomenMarketInterface.java

 

View Code
 1  /*
 2   * To change this template, choose Tools | Templates
 3   * and open the template in the editor.
 4    */
 5  package womenmarket;
 6 
 7  import java.rmi.Remote;
 8  import java.rmi.RemoteException;
 9  import java.util.Hashtable;
10 
11  /**
12   * 20120413
13   *  @author  iltaek
14    */
15  public  interface WomenMarketInterface  extends Remote {
16     
17      public  boolean addWomen(String name,  double Weight)  throws RemoteException;
18      public  boolean removeWomen(String name)  throws RemoteException;
19      public  boolean updateWomen(String name,  double newWeight)  throws RemoteException;
20      public  double getWomen(String name)  throws RemoteException;
21      public Hashtable getAllWomen()  throws RemoteException;
22 
23 }

 

WomenMarcketClient.java

 

 

View Code
  1  /*
  2   * To change this template, choose Tools | Templates
  3   * and open the template in the editor.
  4    */
  5  package womenmarket;
  6 
  7  import java.io.BufferedReader;
  8  import java.io.InputStreamReader;
  9  import java.rmi.Naming;
 10  import java.util.Enumeration;
 11  import java.util.Hashtable;
 12 
 13  /**
 14   * 20120413
 15   *  @author  iltaek
 16    */
 17  public  class WomenMarketClient {
 18 
 19      /**
 20       *  @param  args the command line arguments
 21        */
 22      public  static  void main(String [] args) {
 23             
 24          try {
 25             String name = "WomenMarket";
 26             String addr = "127.0.0.1";
 27 
 28              //  Command line parameter is used as an input -- 
 29               //  this is URL of the registry            
 30               if(args.length > 0) 
 31                 addr = args[0];
 32             
 33              //  find server instance ("Greet") from the rmi registry           
 34              WomenMarketInterface server = (WomenMarketInterface)Naming.lookup("rmi://127.0.0.1:1099/"+name);
 35             
 36             BufferedReader input =  new BufferedReader( new InputStreamReader(System.in));
 37              int choice = 0;
 38              while( true){
 39                 System.out.println("Client-Server Women Market Menu:");
 40                 System.out.println("1. Adding new Women(name-value pair).");
 41                 System.out.println("2. Removing an existing Women(name-value pair).");
 42                 System.out.println("3. Updating an existing Women's value(name-value pair).");
 43                 System.out.println("4. Retrieving a single Women's value(name).");
 44                 System.out.println("5. Retrieving all Womens' values.");
 45                 System.out.println("6. Exit Program.");
 46                 System.out.print(":");
 47                 choice = Integer.parseInt(input.readLine());
 48                 String womenName = "";
 49                  double womenValue = 0;
 50                 
 51                  switch(choice){
 52                     
 53                      case 1:
 54                         System.out.println("> Adding new Women(name-value pair).");
 55                         System.out.println("> Enter Women name: ");
 56                         womenName = input.readLine();
 57                         System.out.println("> Enter Women value: ");
 58                         womenValue = Double.parseDouble(input.readLine());
 59                          if(server.addWomen(womenName, womenValue)){
 60                             System.out.println("> Successful adding a new Women.");
 61                             System.out.println();
 62                         }
 63                          else{
 64                             System.out.println("> Fail adding a new Women.");
 65                             System.out.println();
 66                         }
 67                          break;
 68                         
 69                      case 2:
 70                         System.out.println("> Removing an existing Women(name-value pair).");
 71                         System.out.println("> Enter Women name: ");
 72                         womenName = input.readLine();
 73                          if(server.removeWomen(womenName)){
 74                             System.out.println("> Successful removing the Women.");
 75                             System.out.println();
 76                         }
 77                          else{
 78                             System.out.println("> Fail removing the Women.");
 79                             System.out.println();
 80                         }
 81                          break;
 82                         
 83                      case 3:
 84                         System.out.println("> Updating an existing Women's value(name-value pair).");
 85                         System.out.println("> Enter Women name: ");
 86                         womenName = input.readLine();
 87                         System.out.println("> Enter Women value: ");
 88                         womenValue = Double.parseDouble(input.readLine());
 89                          if(server.updateWomen(womenName, womenValue)){
 90                             System.out.println("> Successful updating the Women.");
 91                             System.out.println();
 92                         }
 93                          else{
 94                             System.out.println("> Fail updating the Women.");
 95                             System.out.println();
 96                         }
 97                          break;
 98                         
 99                      case 4:
100                         System.out.println("> Retrieving a single Women's value(name).");
101                         System.out.println("> Enter Women name: ");
102                         womenName = input.readLine();
103                         Double getWomen = server.getWomen(womenName);
104                          if(getWomen > -1){
105                             System.out.println("> The value of " + womenName + ": " + getWomen);
106                             System.out.println("> Successful retrieving the Women.");
107                             System.out.println();
108                         }
109                          else{
110                             System.out.println("> Fail retrieving the Women.");
111                             System.out.println();
112                         }
113                          break;
114                         
115                      case 5:
116                         System.out.println("> Retrieving a single Women's value(name).");
117                         Hashtable getWomenTable = server.getAllWomen();
118                          if(getWomenTable !=  null){
119                              if(getWomenTable.size() == 0){
120                                     System.out.println("> Empty set.");
121                             }
122                              else{
123                                 Enumeration e = getWomenTable.keys();
124                                  while( e.hasMoreElements() ){
125                                         Object key = e.nextElement();
126                                         System.out.println("> Name: " + key + "\tValue: " + getWomenTable.get(key));
127                                 }
128                             }                            
129                             System.out.println("> Successful retrieving the Women.");
130                             System.out.println();
131                         }
132                          else{
133                             System.out.println("> Fail retrieving the Women.");
134                             System.out.println();
135                         }
136                          break;
137                      case 6:
138                         System.out.println();
139                         System.out.println("Bye Bye~");
140                         System.out.println();
141                         System.exit(0);
142                          break;
143                      default:
144                         System.out.println("> Try another number of menu please.");
145                         System.out.println();
146                         System.exit(0);
147                          break;
148                 }
149             }
150             
151         }  catch (Exception e) {
152             System.err.println("WomenMarketClient exception:");
153             e.printStackTrace();
154         }
155     }
156 }

 

 

 

Java-specific implementation of RMI
Clients interact with server‘s remote interface

Servers extend UnicastRemoteObject or PortableRemoteObject, and implement remote interfaces.

RMI registry is the object directory service for Java RMI
Objects are bound to the registry using string names.
The registry process may execute on any network host.
Client uses RMI URL to connect to the remote object: rmi://serverAddress:1099/RemoteObjectName

 

 

Implementing Java RMI Server and Client
1. Define a remote interface that extends java.rmi.Remote
2. Develop a server object by implementing the remote interface. You
should also extend one of the RemoteObject classes (e.g.
UnicastRemoteObject) which provide remote semantics of Object
by implementing hashCode, equals and toString methods
3. (Use rmic to compile class stub and proxy) [in Java < 5]
4. Start RMI Registry
5. Run the server and bind it to the RMI registry
6. Create a client that performs a lookup for the remote object in the
RMI registry
7. After finding the remote object, the client can invoke its' methods
through the remote interface.
8. Client must handle any exceptions thrown by the remote object

你可能感兴趣的:(mark)