Sunday, January 12, 2014

RMI Java Program 4

// Interface declaration Hello

    import java.rmi.Remote;
    import java.rmi.RemoteException;

    public interface Hello extends Remote {
String sayHello(String s) throws RemoteException;

    }

--------------------------------------------------------------------

//RMI Applet based client

import java.applet.Applet;
import java.awt.Graphics;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class HelloApplet extends Applet { 

    String message = "blank"; 
         
    // "obj" is the identifier that we'll use to refer 
    // to the remote object that implements the "Hello" 
    // interface 
    Hello obj = null; 

    public void init() { 
        try { 
            obj = (Hello)Naming.lookup("//" + 
                getCodeBase().getHost() + "/HelloServer"); 
            message = obj.sayHello(); 
        } catch (Exception e) { 
            System.out.println("HelloApplet exception: " + e.getMessage()); 
            e.printStackTrace(); 
        } 
    } 

    public void paint(Graphics g) { 
        g.drawString(message, 25, 50); 
    } 
}
----------------------------------------------------------------


//RMI Application based client

import java.rmi.RemoteException;

public class HelloClient  { 

    String message = "blank"; 
    Hello obj = null; 

    public void display() { 
        try { 
            obj = (Hello)Naming.lookup("HelloServer"); 
            message = obj.sayHello("hello"); 
   System.out.println(message);
        } catch (Exception e) { 
            System.out.println("HelloApplet exception: " + e.getMessage()); 
            e.printStackTrace(); 
        } 
    } 

    public static void main(String arg[]) { 
        HelloClient  c = new HelloClient();
        c.display();
    } 
}

---------------------------------------------------------------------
//RMI Server 

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements Hello {
    public HelloImpl() throws RemoteException {
super();
    }
    public String sayHello(String s) {
  s = s + " fine";
return s;
    }
    public static void main(String args[]) {
try {
   HelloImpl obj = new HelloImpl();
   // Bind this object instance to the name "HelloServer"
   Naming.rebind("HelloServer", obj);
   System.out.println("HelloServer bound in registry");
} catch (Exception e) {
   System.out.println("HelloImpl err: " + e.getMessage());
   e.printStackTrace();
}
   }
}

---------------------------------------------------------------


HTML code for executing RMI applet based client
<HTML>
<title>Hello World</title>
<center> <h1>Hello World</h1> </center>
<applet code="HelloApplet"   width=500 height=120>
</applet>
</HTML>

Post a Comment