Client Implementation

I will make this program more responsive by running the code that calls the remote method in a separate thread. Now we will use two threads, one for calling the dangerousLoop() method, and the other that takes care of the user interface.

Listing 9.6 MultiThreadClient (Complete client code)

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

//client implementation
public class MultiThreadClient 
	extends JFrame{
	
   //instance variables
   private JTextArea txtMessage;
   private JButton btnStart,btnExit;
   private MultiThreadInterface remote;
	
   //constructor
   public MultiThreadClient(){
		
	super("Multiple Threads");
		
	//get a content pane object
	Container cp = getContentPane();
		
	JPanel btnPanel = new JPanel();

	//text area used to show message
	txtMessage = new JTextArea(8,25);

	//button to call remote method
	btnStart = new JButton("Start");

	//button to exit application
	btnExit = new JButton("Exit");

	//add action listener to buttons.
	ButtonHandler handler = new ButtonHandler();
	btnStart.addActionListener(handler);
	btnExit.addActionListener(handler);
	
	//add components to containers
	btnPanel.add(btnStart);btnPanel.add(btnExit);
	cp.add(txtMessage);
	cp.add(btnPanel,BorderLayout.SOUTH);
	try{

//get a remote reference remote = (MultiThreadInterface)Naming.lookup("Server"); }catch(Exception ex){ txtMessage.setText(ex.getMessage()); } //set the default close operation
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //pack() causes the window to be sized to fit the //preferred size and layouts of its subcomponents. pack(); //Make the Window visible. show(); } //main method public static void main(String args[]){ new MultiThreadClient(); } //Thread related code private class ThreadHandler implements Runnable{ public void run(){ try{ txtMessage.setText("Calling remote method"); String msg = remote.dangerousLoop(); txtMessage.setText(msg); }catch(Exception ex){ txtMessage.setText(ex.getMessage()); } } } //Event handling class private class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent ae){ JButton temp = (JButton)ae.getSource(); if(temp == btnStart){ ThreadHandler th = new ThreadHandler(); Thread thread = new Thread(th); thread.start(); } else{ System.exit(0); } } } }
 

 

RMI BOOK MAIN PAGE                Top

  
Copyright © 2001 www.universalteacher.com