RMI-Example-2
This example
demonstrate the RMI Addition Application. Well in this application you will use
the four java files. List of java files and their code are shown below:
Code:
RemoteInterface.java
import java.rmi.*;
public interface RemoteInterface extends Remote
{
public int add(int x,int y)throws Exception;
}
|
ServerImplements.java
import java.rmi.*;
import java.rmi.server.*;
import java.lang.String;
interface RemoteInterface extends Remote {
public int add(int x, int y) throws Exception;
}
public class ServerImplements extends UnicastRemoteObject implements
RemoteInterface {
public ServerImplements() throws Exception {
super();
}
public int add(int x, int y) {
return (x + y);
}
}
|
Server.java
import java.rmi.*;
import java.net.*;
public class Server {
public static void main(String args[]) {
try {
ServerImplements s = new ServerImplements();
Naming.rebind("RMIAPPLICATION", s);
System.out.println("Server has been started");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Client.java
import java.rmi.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Client extends JFrame {
TextField t1 = new TextField(30);
TextField t2 = new TextField(30);
Label rs = new Label("Sum= 0");
JButton b = new JButton("Add");
Panel p = new Panel(new GridLayout(4, 1, 5, 5));
RemoteInterface s;
public Client() {
super("Client Side");
setSize(250, 250);
setLocation(300, 300);
getContentPane().add(p, "North");
p.add(t1);
p.add(t2);
p.add(rs);
p.add(b);
try {
String ipp = JOptionPane
.showInputDialog("Please enter the IP Address to Connect");
String ip = "rmi://" + ipp + "/RMIAPPLICATION";
s = (RemoteInterface) Naming.lookup(ip);
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
try {
int r = s.add(a, b);
rs.setText("Sum of two no =" + r);
} catch (Exception epx) {
}
}
});
}
public static void main(String args[]) {
Client c = new Client();
c.setDefaultCloseOperation(EXIT_ON_CLOSE);
c.setVisible(true);
}
}
|
Steps for execution:
Step-1
javac RemoteInterface.java
javac ServerImplements.java
Step-2
rmic ServerImplements
This steps create Stub/ Skeleton
Step-3
javac Server.java
javac Client.java
Step-4
Open Two More Consoles. by writing 'start' twice.
Step-5
On first console
rmiregistry
Step-6
On second console
java Server
Step-7
On third console
java Client
This steps can be seen in the following pictures also: