Home : Course Map : Chapter 20 :
Client Demo
JavaTech
Course Map
Chapter 20

Introduction
Simulation
Server Demo
Client Demo
Demo Support

Exercises

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The client demo directs the server to run the simulation and send back the results. The directory path for the package for the Client class goes as

javatech
   |
   |__ all20
                    |
                    |__ client

 

Client.java

package javatech.all20.client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import javatech.all20.server.FactoryInterface;
import javatech.all20.server.ServerInterface;

import javatech.utils.hist.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client
{
  // This name must match the values used by the server.
  //final private static String FACTORY_NAME = "all20ServerFactory";

  // This sets the size of the output data array. It must match what is used
  // by the server.
  final private static int OUTSIZE = 6;

  // Default values for the simulation parameters.
  private float fAmp = 1.f, fOmega=1.f, fSpringCons = 1.f;
  private float fDeltaT=0.1f, fMaxTime=2.f*(float)Math.PI;
  private float fControl = 1.f;
  private int fNumBins = 21;
  private float[] fIndata;

  // References to the factory and server.
  private FactoryInterface fFactory;
  private ServerInterface fServer;

  private boolean fReallyQuit;

  private Histogram fPositionHist, fVelocityHist, fTimeHist, fOmegaTimeHist;
  private HistPanel fPositionHPan, fVelocityHPan, fTimeHPan, fOmegaTimeHPan;

  private Histogram fKEHist,fPEHist;
  private HistPanel fKEPanel, fPEPanel;

  private JButton fQuitButton = new JButton ("Quit");

  private final boolean DO_TIME_HIST = true;
  private final boolean DO_VELOCITY_HIST = true;
  private final boolean DO_OMEGA_TIME_HIST = true;
  private final boolean DO_KE_HIST = true;
  private final boolean DO_PE_HIST = true;

  /** ctor **/
  public Client () {
    fQuitButton.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent ev) {
        if (fReallyQuit)
          // If we've been here before, then really quit this time.
          System.exit (0);
        else {
          // If not, set the control flag to tell the server to halt
          // the simulation.
          fIndata[5] = 1.f;
          fReallyQuit = true;
          fQuitButton.setText ("One more time to exit");
        }
      } // actionPerformed
    });

    try {
      // Find the server factory.
      String host = System.getProperty ("server.host", "localhost");
      String port = System.getProperty ("server.port", "3001");
      String factory_server = "//" + host + ":" + port +
        "/"+FactoryInterface.FACTORY_NAME;
      System.err.println ("Client ctor: looking up factory " + factory_server);
      fFactory = (FactoryInterface) Naming.lookup (factory_server);
      System.err.println ("Client ctor: got it, getting user.name");
      String uid = System.getProperty ("user.name");
      System.err.println (
        "Client ctor: uid = " + uid + ", calling factory.getInstance()");
      // Get a server instance from the server factory.
      fServer = fFactory.getInstance (uid);
      System.err.println ("Client ctor: got the server instance");
    } // try
    catch (MalformedURLException mue) {
      System.err.println (mue);
    }
    catch (NotBoundException nbe) {
      System.err.println (nbe);
    }
    catch (RemoteException re) {
      System.err.println (re);
    }
    if (fFactory == null || fServer == null) {
      System.err.println ("\nEXITING BECAUSE OF FAILURE");
      System.exit (1);
    }
  } // ctor


  public void setParameters (String[] args) {
    switch (args.length) {
      case 6:
        fNumBins  = Integer.parseInt (args[5]);
      case 5:
        fMaxTime  = Float.parseFloat (args[4]) * (float) Math.PI;
      case 4:
        fDeltaT   = Float.parseFloat (args[3]);
      case 3:
        fSpringCons = Float.parseFloat (args[2]);
      case 2:
        fOmega   = Float.parseFloat (args[1]);
      case 1:
        fAmp    = Float.parseFloat (args[0]);
    } // switch
    fPositionHist = new Histogram ("Position (x) ", "", fNumBins, -fAmp, fAmp);
    fPositionHPan = new HistPanel (fPositionHist);
    JFrame position_frame = new JFrame ("Position Histogram");
    position_frame.getContentPane().add (fPositionHPan);
    position_frame.getContentPane().add (fQuitButton, BorderLayout.SOUTH);
    int width = 680;
    int height = 380;
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width - width) / 2;
    int y = (screen.height - height) / 3;
    position_frame.setBounds(x, y, width, height);
    position_frame.setVisible (true);
    if (DO_VELOCITY_HIST) {
      JFrame velocity_frame = new JFrame ("Velocity Histogram");
      fVelocityHist = new Histogram ("velocity", "", fNumBins, -fOmega*fAmp,
                                     fOmega*fAmp);
      fVelocityHPan = new HistPanel (fVelocityHist);
      velocity_frame.getContentPane().add (fVelocityHPan);
      velocity_frame.setBounds(700, 0, width, height);
      velocity_frame.setVisible (true);
    }

    if (DO_KE_HIST) {
      JFrame ke_frame;
      fKEHist = new Histogram ("KE", "", fNumBins, 0.,
                               0.5f*fOmega*fOmega*fAmp*fAmp);
      fKEPanel = new HistPanel (fKEHist);
      ke_frame = new JFrame ("Kinetic Energy Histogram");
      ke_frame.getContentPane().add (fKEPanel);
      ke_frame.setBounds(0, 0, width, height);
      ke_frame.setVisible (true);
    }

    if (DO_PE_HIST) {
      JFrame ke_frame;
      fPEHist = new Histogram ("PE", "", fNumBins, 0.,
                               0.5f*fOmega*fOmega*fAmp*fAmp);
      fPEPanel = new HistPanel (fPEHist);
      ke_frame = new JFrame ("Potential Energy Histogram");
      ke_frame.getContentPane().add (fPEPanel);
      ke_frame.setBounds(0, height+100, width, height);
      ke_frame.setVisible (true);
    }

    if (DO_TIME_HIST) {
      JFrame time_frame;
      fTimeHist = new Histogram ("t", "", fNumBins, 0., fMaxTime);
      fTimeHPan = new HistPanel (fTimeHist);
      time_frame = new JFrame ("Time Histogram");
      time_frame.getContentPane().add (fTimeHPan);
      time_frame.setBounds(0, 0, width, height);
      time_frame.setVisible (true);
    }

    if (DO_OMEGA_TIME_HIST) {
      JFrame omega_time_frame;
      omega_time_frame = new JFrame ("Omega Time Histogram");
      fOmegaTimeHist = new Histogram ("omega*t%2pi", "", fNumBins, 0.,
                                      2.f*Math.PI);
      fOmegaTimeHPan = new HistPanel (fOmegaTimeHist);
      omega_time_frame.getContentPane().add (fOmegaTimeHPan);
      omega_time_frame.setBounds(0, height+100, width, height);
      omega_time_frame.setVisible (true);
    }
  } // setParameters


  public void runSimulation () {
    // Initialize the server.
    // Server calculates sin (omega * t) where omega is an input variable
    // and t is the simulation time.
    try {
      System.err.println ("Client.runSimulation: calling server.initialize");
      boolean server_status = fServer.initialize ("doesn't matter");
      if (!server_status) {
        System.err.println ("Server initialization failed.");
        System.exit (1);
      }
    } // try
    catch (RemoteException re) {
      System.err.println ("Server initialization failed:");
      System.err.println (re);
      System.exit (1);
    }

    // Initialize the simulation.
    try {
      System.err.println (
       "Client.runSimulation: calling server.initializeSimulation");
      System.err.println ("Client.runSimulation: initial params are amp = " +
        fAmp + " omega = " + fOmega + " K = " + fSpringCons + " dt = " +
        fDeltaT + " tmax = " + fMaxTime/(float)Math.PI + "pi (" +
        fNumBins + " bins)");
      fIndata = new float[] {
        fAmp, fOmega, fSpringCons, fDeltaT, fMaxTime, 0.f
      };
      fServer.initializeSimulation (fIndata);
    } // try
    catch (RemoteException re) {
      System.err.println ("Simulation initialization failed:");
      System.err.println (re);
      System.exit (1);
    }

    // Set up variables to contain results from simulation.
    float[] outdata = new float[OUTSIZE];
    float last_sim_time = -1.f;
    float time, xposition, velocity, acceleration, kinetic, potential;
    float total_energy;
    int total_hits = 0;

    // Start the simulation running.
    try {
      System.err.println ("Client.runSimulation: calling server.start");
      System.err.println (
        "Output will be omega*t, xpos, vel, acc, KE, PE, total E");
      fServer.start ();
    } // try
    catch (RemoteException re) {
      System.err.println ("Simulation failed to start:");
      System.err.println (re);
      System.exit (1);
    }

    // Retrieve data from the simulation.
    try {
      // Wait on first valid value.
      outdata[0] = -1.f;
      while (outdata[0] < 0.f) {
        outdata = fServer.retrieveData (fIndata);
        Thread.sleep (80);
      }
      // Process real values.
      while (outdata[0] >= 0.f) {
        time     = outdata[0];
        xposition  = outdata[1];
        velocity   = outdata[2];
        acceleration = outdata[3];
        kinetic   = outdata[4];
        potential  = outdata[5];
        total_energy = kinetic + potential;

        if (time > last_sim_time) {
          total_hits++;
          last_sim_time = time;
          float omtopi = fOmega * time / (float)Math.PI;
          System.err.println (
            omtopi + " pi " + xposition + " " + velocity + " " +
            acceleration + " " + kinetic + " " + potential + " " +
            total_energy
          );
          fPositionHist.add (xposition);
          fPositionHPan.repaint ();
          if (DO_VELOCITY_HIST) {
            fVelocityHist.add (velocity);
            fVelocityHPan.repaint ();
          }
          if (DO_KE_HIST) {
            fKEHist.add (kinetic);
            fKEPanel.repaint ();
          }
          if (DO_PE_HIST) {
            fPEHist.add (potential);
            fPEPanel.repaint ();
          }
          if (DO_TIME_HIST) {
            fTimeHist.add (time);
            fTimeHPan.repaint ();
          }
          if (DO_OMEGA_TIME_HIST) {
            fOmegaTimeHist.add ((fOmega*time)%(2.*Math.PI));
            fOmegaTimeHPan.repaint ();
          }
        } // if current sim time > previous sim time
        else {
          if (time < 0.f)
            System.err.println ("Negative time " + time +
              " signals end of simulation from server");
          else
            System.err.println (
              "Client.runSimulation: ignoring repeated data time");
        }
        // Sleep long enough for the server to have probably calculated
        // the next set of values.
        Thread.sleep (80);
        // Get new set of data from server.
        outdata = fServer.retrieveData (fIndata);
      } // while simulation is still running
    } // try
    catch (RemoteException re) {
      System.err.println ("\nUGH, server is no longer responding");
    }
    // InterruptedException intentionally ignored.
    catch (InterruptedException ie) {
      System.err.println (
        "Client.runSimulation: InterruptedException ignoered");
    }
    System.err.println ("Client.runSimulation: while loop completed (" +
      total_hits + " total unique hits)");
    int left_edge_bin = 0;
    int central_bin = (fNumBins-1)/2;
    int right_edge_bin = fNumBins-1;
    int left_hits = fPositionHist.getValue (left_edge_bin);
    int central_hits = fPositionHist.getValue (central_bin);
    int right_hits = fPositionHist.getValue (right_edge_bin);
    float left_frac = (float) left_hits / total_hits;
    float central_frac = (float) central_hits / total_hits;
    float right_frac = (float) right_hits / total_hits;
    System.err.println ("Client.runSimulation: #hits at left edge bin (0) = " +
      left_hits + " frac = " + left_frac);
    System.err.println ("Client.runSimulation: #hits at central bin (" +
      central_bin + ") = " + central_hits + " frac = " + central_frac);
    System.err.println ("Client.runSimulation: #hits at right edge bin (" +
      right_edge_bin + ") = " + right_hits + " frac = " + right_frac);
    System.err.println ("\nClient.runSimulation: params were " + fAmp + " " +
      fOmega + " " + fSpringCons + " " + fDeltaT + " " +
      fMaxTime/(float)Math.PI + "(*pi) " + fNumBins);
    fReallyQuit = true;
  } // runSimulation


  public static void main (String[] args) {
    System.err.println ("main: Instantiating a new Client");
    Client cl = new Client ();
    System.err.println ("main: Calling Client.setParameters()");
    cl.setParameters (args);
    System.err.println ("main: Calling Client.runSimulation()");
    cl.runSimulation ();
    System.err.println ("main: back from runSimulation(), main is terminating");
    System.err.println (
   "main: to run again, optional params are amp, omega, K, dt, tmax, num bins");
  } // main
} // Client

 

 

Most recent update: Oct. 14, 2005

  
  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.