2009-09-15

Create a Chat server in Java RMI

Create the Interface class as follows and name it as Inter.java

import java.rmi.*;

public interface Inter extends Remote
{
  public void chat(Integer a,String b) throws RemoteException;
  public String get(Integer a) throws RemoteException;
  public String get() throws RemoteException;
}

Create the Server class as follows and name it as Chat_server.java

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

public class Chat_server extends UnicastRemoteObject implements Inter{

    static HashMap<Integer, ArrayList> messages=new HashMap<Integer, ArrayList>();

    Chat_server() throws RemoteException{
        super();
    }

    public void chat(Integer a, String msg) throws RemoteException{

        boolean flag = false;

    if(!messages.isEmpty()){
    Integer numbers[] = new Integer[messages.size()];
    messages.keySet().toArray(numbers);

    for(int i=0;i<numbers.length;i++){

        if(a.intValue()==numbers[i].intValue()){
        ArrayList temp;
        temp=messages.get(a);
        temp.add(msg);
        messages.put(a, temp);
        flag=true;
        }

    }

    }

    if(!flag){
            ArrayList<String> al=new ArrayList<String>();
            al.add(msg);
            messages.put(a, al);
    }

    }

    public String get(Integer a) throws RemoteException{

        Integer numbers[] = new Integer[messages.size()];
        messages.keySet().toArray(numbers);
        boolean flag = false;

    for(int i=0;i<numbers.length;i++){

        if(a.intValue()==numbers[i].intValue()){
        ArrayList temp;
            temp=messages.get(a);
            Iterator b=temp.iterator();
            String all_messages="<html>", all="";
            flag=true;

            while(b.hasNext()){
                all_messages=(String) b.next();
                all+=(all_messages+"<br>");
            }

            return "<html>"+all;

        }

    }

        if(!flag){
            return "There are no messages from Client "+a;
        }

        return "test";

    }
   
    //method used for polling
   
    public String get() throws RemoteException{

        Set s=messages.keySet();
        Iterator use=s.iterator();
        String all="";

    while(use.hasNext()){

        ArrayList temp;
        int temp_no=(Integer)use.next();
            temp=messages.get((Integer)temp_no);
            String all_messages="";

            if(temp!=null){
            Iterator b=temp.iterator();
            String final_messages="<html><I><tt>Message to Client "+temp_no+": </tt></I>";

            while(b.hasNext()){
                all_messages=final_messages+(String) b.next();
                all+=(all_messages+"<br>");
            }

            }
           
    }

    return all;

    }

    public static void main(String args[]){

        try{
        System.setSecurityManager(new RMISecurityManager());
        //set the security manager

        //create a local instance of the object
        Chat_server server = new Chat_server();

        //put the local instance in the registry
        Naming.rebind("CHAT-SERVER" , server);

        System.out.println("Server waiting.....");
        }

        catch (java.net.MalformedURLException me){
        System.out.println("Malformed URL: " + me.toString());
        }

        catch (RemoteException re){
        System.out.println("Remote exception: " + re.toString());
        }

    }

}

Create the Client class as follows and name it as NewJFrame.java

import java.rmi.*;
import java.rmi.server.*;

public class NewJFrame extends javax.swing.JFrame {

    public NewJFrame() {
        initComponents();
        strart();
        strart1();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jToggleButton1 = new javax.swing.JToggleButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat System");
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(0, 0, 0));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Send");
        jButton1.setToolTipText("Send Message");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Client Number");

        jButton2.setText("Receive");
        jButton2.setToolTipText("Receive Messages");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Client Number");

        jButton3.setForeground(new java.awt.Color(255, 0, 0));
        jButton3.setText("Exit");
        jButton3.setToolTipText("Exit the Chat System");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jToggleButton1.setForeground(new java.awt.Color(0, 0, 255));
        jToggleButton1.setText("Enable polling");
        jToggleButton1.setToolTipText("Push for enable");
        jToggleButton1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEtchedBorder(), javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)));
        jToggleButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(65, 65, 65)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(79, 79, 79))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                            .addComponent(jToggleButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(70, 70, 70)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(72, 72, 72))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(194, 194, 194))))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToggleButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
       
            // set the security manager for the client
            System.setSecurityManager(new RMISecurityManager());
     
            //get the remote object from the registry
            try{
            System.out.println("Security Manager loaded");
            String url = "//localhost/CHAT-SERVER";
            Inter remoteObject = (Inter)Naming.lookup(url);
            System.out.println("Got remote object");
            Integer i=Integer.parseInt(jTextField1.getText());
            String message=jTextArea1.getText();
            remoteObject.chat(i, message);
            System.out.println(" Sent message ");
            }
           
            catch (RemoteException exc){
            System.out.println("Error in lookup: " + exc.toString());
            }
       
            catch (java.net.MalformedURLException exc){
            System.out.println("Malformed URL: " + exc.toString());  
            }
       
            catch (java.rmi.NotBoundException exc){
            System.out.println("NotBound: " + exc.toString());
            }
       
    }
   
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
       
            // set the security manager for the client
            System.setSecurityManager(new RMISecurityManager());
     
            //get the remote object from the registry
            try{
            System.out.println("Security Manager loaded");
            String url = "//localhost/CHAT-SERVER";
            Inter remoteObject = (Inter)Naming.lookup(url);
            System.out.println("Got remote object");
            Integer i=Integer.parseInt(jTextField2.getText());
            System.out.println(" Got message ");
            String all=remoteObject.get(i);
            jLabel2.setText(all);
            }
           
            catch (RemoteException exc){
            System.out.println("Error in lookup: " + exc.toString());
            }
       
            catch (java.net.MalformedURLException exc){
            System.out.println("Malformed URL: " + exc.toString());  
            }
       
            catch (java.rmi.NotBoundException exc){
            System.out.println("NotBound: " + exc.toString());
            }
    }
   
    //polling mechanism
   
    private class Poll extends Thread{
   
        public void run(){
       
        while(true){
            // set the security manager for the client
            System.setSecurityManager(new RMISecurityManager());
     
            //get the remote object from the registry
            try{
            System.out.println("Security Manager loaded");
            String url = "//localhost/CHAT-SERVER";
            Inter remoteObject = (Inter)Naming.lookup(url);
            System.out.println(" Got message ");
            String all=remoteObject.get();
            jLabel2.setText(all);
            Poll.sleep(10000);
            }
           
            catch (RemoteException exc){
            System.out.println("Error in lookup: " + exc.toString());
            }
       
            catch (java.net.MalformedURLException exc){
            System.out.println("Malformed URL: " + exc.toString());  
            }
       
            catch (java.rmi.NotBoundException exc){
            System.out.println("NotBound: " + exc.toString());
            }
           
            catch (InterruptedException ex) {
            }
           
        }
       
        }
   
    }
   
    Poll p=new Poll();
   
    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        if(jToggleButton1.isSelected()){
            p=new Poll();
            jLabel4.setText("Polling enables");
            p.start();
        }
        else{
            jLabel4.setText("Polling disabled");
                p.stop();
        }
    }
   
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        System.exit(0);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
   
    private class Animate extends Thread{

        public void run(){
            String str=new String();
            str="Exit";

            for(;;){
                    for(int i=0; i<=str.length();i++){
                     jButton3.setText(str.substring(0, i));
                try {
                    Animate.sleep(200);
                } catch (InterruptedException ex) {
                }
                if(i==str.length()){
                try {
                    Animate.sleep(2000);
                } catch (InterruptedException ex) {
                }
                }
                    }
            }

        }

    }
   
        private class Animate1 extends Thread{

        public void run(){
            String str=new String();
            str="CHAT SYSTEM - CREATED BY RUCHIRA CHANAKA";

            for(;;){
                    for(int i=0; i<=str.length();i++){
                     setTitle(str.substring(0, i));
                try {
                    Animate1.sleep(200);
                } catch (InterruptedException ex) {
                }
                if(i==str.length()){
                try {
                    Animate1.sleep(2000);
                } catch (InterruptedException ex) {
                }
                }
                    }
            }

        }

    }
   
    private void strart1(){
    Animate1 a=new Animate1();
    a.start();
    }

    private void strart(){
    Animate a=new Animate();
    a.start();
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration

}

Open the Command Prompt

  • Change directory to the current working directory (RMI)
  • Compile the interface class
    • “javac Inter.java”
  • Compile the Server class
    • “javac Chat_server.java”
  • Generate the stub
    • “rmic Chat_server”
  • Compile the Client class
    • “javac NewJFrame.java”
  • Start the RMI registry
    • “start rmiregistry”
  • Start the server
    • “java -Djava.security.policy=policy.all Chat_server” 
    clip_image002

  • Start the Client
    • “java -Djava.security.policy=policy.all NewJFrame”


image image 


    No comments: