Client Implementation
Listing
11.4 RemoteClientImpl.java
//import packages
import java.rmi.*;
import java.rmi.server.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//client implementation
public class RemoteClientImpl extends
JFrame implements ClientInterface {
//variable declaration
private JButton btnSend;
private JTextArea txtReceive,txtPass;
private ServerInterface server;
//constructor
public RemoteClientImpl()
throws RemoteException{
super("Remote Client");
System.out.println("Creating remote client");
this.setup();
}
//method used to create various components
private void setup(){
//get the content pane object
Container cp = getContentPane();
//panel for buttons
JPanel btnPanel = new JPanel();
//text area used to show received messages.
txtReceive = new JTextArea(15,45);
txtReceive.setBorder(BorderFactory.createTitledBorder(
"Messages Received"));
txtReceive.setEditable(false);
//text area for typing messages.
txtPass = new JTextArea(5,45);
txtPass.setBorder(BorderFactory.createTitledBorder(
"Type your message here"));
//button to post a message
btnSend = new JButton("Send Message");
//add action listener
btnSend.addActionListener(new ButtonHandler());
JScrollPane
cPane = new JScrollPane(txtReceive),
sPane = new JScrollPane(txtPass);
//add all the components
btnPanel.add(btnSend);
cp.add(cPane,BorderLayout.NORTH);
cp.add(sPane,BorderLayout.CENTER);
cp.add(btnPanel,BorderLayout.SOUTH);
//method used to register with the server
register();
//set default close operation
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//pack the frame and show it
pack();
show();
txtPass.requestFocus();
}
//method used to register with the server
private void register(){
try{
//get a remote reference
server = (ServerInterface)Naming.lookup("Server");
//export the object explicitly
UnicastRemoteObject.exportObject(this);
//get registered with the server
server.getRegistered(this);
txtReceive.append("Registered with the server");
}catch(Exception ex){
txtReceive.append(ex.getMessage());
}
}
//remote method used to post a message to the
//client.
public void passMessage(String message)
throws RemoteException{
txtReceive.append(message);
}
//create an instance of the client
public static void main(String args[]){
try{
RemoteClientImpl cl = new RemoteClientImpl();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
//event handling class
private class ButtonHandler
implements ActionListener{
public void actionPerformed(ActionEvent ae){
try{
//post message to the server
server.passMessage("\n"+txtPass.getText());
txtPass.setText("");
txtPass.requestFocus();
}catch(Exception ex){
txtReceive.append(ex.getMessage());
}
}
}
}
|