Tuesday, September 1, 2015

RMI-REMOTE METHOD INVOCATION: IN JAVA

RMI SERVER:-

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.Scanner;

public class RmiServe
{
    public static void main(String args[])
    {
        try
        {
            RmiImpl stub=new RmiImpl();
             Registry reg=LocateRegistry.createRegistry(1099);
            reg.rebind("server", stub);
            System.out.println("SERVER STARTED...");
            while(true)
            {
                Scanner in=new Scanner(System.in);
               
                String msg=in.nextLine().trim();
                if(stub.getClient()!=null)
                {
                    RmiInterc cli=stub.getClient();
                    cli.send(msg);
                   
                }
               
               
            }
           
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
}
}
RMI CLIENT:-

import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;

public class RmiClients
{
   public static void main(String args[]) throws RemoteException, NotBoundException
   {
     RmiImpl rm=new RmiImpl();
     Registry reg=LocateRegistry.getRegistry("127.0.0.1",1099);
       RmiInterc rmi=(RmiInterc)reg.lookup("server");
        System.out.println("CONNECTED TO SERVER");
        rmi.setClient(rm);
        while(true)
            {
                Scanner in=new Scanner(System.in);
            System.out.println("ENTER VALUE");
            String msg=in.nextLine().trim();
            rmi.send(msg);
            }
      
   }
}
RMI INTERFACE:

public interface RmiInterc extends Remote
{
 public void send(String msg) throws RemoteException;
  public void setClient(RmiInterc c)throws RemoteException;
  public RmiInterc getClient() throws RemoteException;

}
RMI IMPLEMENTING CLASS:

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class RmiImpl extends UnicastRemoteObject implements RmiInterc
{
         String dat;
    public RmiInterc client=null;
     RmiImpl() throws RemoteException
    {
        super();
    }
   
    public void send(String s) throws RemoteException
        {
                                System.out.println(s);
               
        }
      public void setClient(RmiInterc c)throws RemoteException
    {
        client=c;
       
    }
                public RmiInterc getClient() throws RemoteException
        {
            return client;
        }
   

}

No comments:

Post a Comment