Kategorien
Java

Java RPC/Reflection Client Server Kommunikation

Das Parkhausbeispiel unter Verwendung eines RPC (Remote Procedure Call). Dabei wird über Reflection die Klasse auf dem Server zur Laufzeit instanziiert und eine beliebige Methode mit Parametern aufgerufen, die der Client bestimmen kann.

Client:

public class Client {
    public static void main(String[] args) throws IOException {

        Socket kkSocket = null;

        try {
            kkSocket = new Socket("127.0.0.1", 6700);
        } catch (UnknownHostException e) {
            System.err.println("host unknown.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: 127.0.0.1.");
            System.exit(1);
        }
       BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
       String fromUser;
       String paramsIn;
       ObjectOutputStream oos = new ObjectOutputStream(kkSocket.getOutputStream());
       ObjectInputStream ois = new ObjectInputStream(kkSocket.getInputStream());
        while (true) {
                //schicke Input zum Server
              try
                {
                  fromUser = stdIn.readLine();

                  String[] paramsUser = fromUser.split("\\s+");
                  if(paramsUser.length == 1)
                  {
                    Object[] params = {paramsUser[0]};
                    System.out.println("Stream writing: Param0: " + params[0]);
                    oos.writeObject(params);
                    if(paramsUser[0].equals("exit"))
                    {
                        break;
                    }
                  }
                  else if(paramsUser.length == 2)
                  {
                    Object[] params = {paramsUser[0], paramsUser[1]};
                    System.out.println("Stream writing: Param0: " + params[0] + " Param1: " + params[1]);
                    oos.writeObject(params);
                  }
                  else
                  {
                    throw new IllegalArgumentException();
                  }
                }
                catch(IllegalArgumentException ex)
                {
                  System.out.println("ungueltige Eingabe");
                }

                //lese Antwort vom Server
                try {

                    paramsIn = (String) ois.readObject();
                    System.out.println("Antwort Server: " + paramsIn);
                } catch (ClassNotFoundException ex) {
                    System.out.println("Class not found.");
                    break;
                }                
        }
        oos.close();
        oos.close();
        System.out.println("Client down.");
        stdIn.close();
        kkSocket.close();

    }
}

Server:

public class Server {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(6700);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 6700.");
            System.exit(1);
        }
        System.out.println("Server Running.");
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }
        ParkhausService parkhausService = new ParkhausService();
        Class parkhausServiceClass = parkhausService.getClass();

        ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
        ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());

        Object[] paramsIn = null;
        Method m = null;
        String returnReflection = null;
        while (true) {
            returnReflection = "";
            //lese Input vom Client
            try {
                paramsIn = (Object[]) ois.readObject();                
                String searchFunction = (String) paramsIn[0];                   
                try {
                    if(paramsIn.length == 1)
                    {
                      if(paramsIn[0].equals("exit"))
                      {
                          break;
                      }
                       m = parkhausServiceClass.getDeclaredMethod(searchFunction);
                       System.out.println("Method found: " + m.toString());
                       System.out.println("Stream reading: Param0: " + paramsIn[0]);
                       returnReflection = (String) m.invoke(parkhausService);
                    }
                    else if(paramsIn.length == 2)
                    {
                       Class[] parameterClass = new Class[1];
                       parameterClass[0] =  Integer.TYPE;
                       m = parkhausServiceClass.getDeclaredMethod(searchFunction, parameterClass);
                       System.out.println("Method found: " + m.toString());
                       System.out.println("Stream reading: Param0: " + paramsIn[0] + " Param1: " + paramsIn[1]);
                       int parameterInt =  Integer.parseInt(String.valueOf(paramsIn[1]));
                       returnReflection = (String) m.invoke(parkhausService,  parameterInt);
                    }
                    else
                    {
                      throw new IllegalArgumentException("falsche Parameter Anzahl Eingabe");
                    }
                } catch (Exception ex) {
                     returnReflection = returnErrorMessage(ex);
                }
            } catch (ClassNotFoundException ex) {
                returnReflection = returnErrorMessage(ex);
                break;
            }
            //schicke Output an Client
            System.out.println("Stream to Client Sending:" + returnReflection.toString());
            oos.writeObject(returnReflection.toString());
        }
        System.out.println("Server Down.");
        ois.close();
        oos.close();

        clientSocket.close();
        serverSocket.close();

    }
    public static String returnErrorMessage(Exception ex)
    {
        String message = ex.getClass().getSimpleName() + " Message:" + ex.getMessage();
        System.out.println(message);
        ex.printStackTrace();
        return message;
    }
}

ParkhausService:

public class ParkhausService {
    private Parkhaus _parkhaus = null;

    public ParkhausService()
    {
        _parkhaus = new Parkhaus(5);
    }
    public String in(int anzahlAutos)
    {
            try
            {
                _parkhaus.einfahrenAuto(anzahlAutos);
                return anzahlAutos + " Autos eingefahren";
            }
            catch(IllegalStateException ex)
            {
                return "Fehler beim Einfahren";
            }
        }

    public String out(int anzahlAutos)
    {
            try
            {
                _parkhaus.rausfahrenAuto(anzahlAutos);
                return anzahlAutos + " Autos rausgefahren";
            }
            catch(IllegalStateException ex)
            {
                return "Fehler beim Rausfahren";
            }
    }
    public String free()
    {
            try
            {
                int freiParkplaetze = _parkhaus.freieParkplaetze();
                return freiParkplaetze + " freie Parkplaetze";
            }
            catch(IllegalStateException ex)
            {
                return "Fehler freie Parkplaetze";
            }
    }
}