Client Implementation
Listing 7.3 (TimecalClient.java)
import java.rmi.*;
import java.net.MalformedURLException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//Client implementation
public class TimecalClient extends JFrame{
//instance variables
private JTextArea txtArea = null;
private JButton
btnLocal = null,
btnRemote = null;
private TimecalInterface server= null;
//constructor
public TimecalClient(){
super("Time calculator");
Container cp = getContentPane();
JPanel btnPanel = new JPanel();
txtArea = new JTextArea(10,50);
//button used to call the remote method
btnRemote = new JButton("Remote Call");
//button used to call the local method
btnLocal = new JButton("Local Call");
//listener
ButtonHandler handler = new ButtonHandler();
btnRemote.addActionListener(handler);
btnLocal.addActionListener(handler);
btnPanel.add(btnRemote);btnPanel.add(btnLocal);
cp.add(txtArea);
cp.add(btnPanel,BorderLayout.SOUTH);
try{
//get a remote reference
server = (TimecalInterface)Naming.lookup("Server");
}catch(RemoteException ex) {
txtArea.setText("Error " +ex.getMessage());
}
catch(MalformedURLException ex) {
txtArea.setText("Error " +ex.getMessage());
}
catch(NotBoundException ex) {
txtArea.setText("Error " +ex.getMessage());
}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocation(10,10);
show();
}
//main method
public static void main(String []client) {
new TimecalClient();
}
//local method
private String localCall(String text){
int i=0;
for(i=0;i<100;i++)
System.out.println(text +" "+i);
return text;
}
//Event handling class
private class ButtonHandler
implements ActionListener{
public void actionPerformed(ActionEvent ae){
JButton temp = (JButton)ae.getSource();
long before,after;
if(temp == btnRemote){
try{
before = System.currentTimeMillis();
String msg = server.remoteCall("Time taken by remote call:");
after = System.currentTimeMillis();
msg += after - before;
txtArea.setText("\n"+ msg);
}catch(Exception ex){
txtArea.setText("Error :"+ex.getMessage());
}
}
else{
before = System.currentTimeMillis();
String msg = localCall("Time taken by local call: ");
after = System.currentTimeMillis();
msg += after - before;
txtArea.setText("\n" + msg);
}
}
}
}
Explanation
The constructor creates a number of components and containers. It creates
a TextArea to show messages and two instances of buttons. The remote
call button calls the remote method and the local call button calls
the local method. It adds event listener to the buttons. Finally, it
obtains a reference to the remote object and shows the window. The main
method just creates an instance of the Client application. The localCall()
method simply returns the string passed to it.
The ButtonHandler class handles the
action events generated by the two buttons. It first checks the source
of the event and then calls the appropriate method. You can start the
application and see the result.
Figure 7.1

|