views:

24

answers:

2

I am writing a RMI chat program. In my program I am able to receive and send messages, but i am not able to display it in the TextArea. I am not sure what is the error. I tried using Event Dispatch method also. It doesn't help.

public class client extends javax.swing.JFrame implements inter {

public client() {
    initComponents();
}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        final inter i = (inter) Naming.lookup("rmi://localhost:1111/client1");
        final String msg = jTextField1.getText();
        if (msg.length() > 0) {
            jTextArea1.append("Me :" + msg);
            java.awt.EventQueue.invokeLater(new Runnable() {

                public void run() {
                    try {
                        i.rcvMsg("Client 1 : " + msg);
                    } catch (RemoteException ex) {
                    }
                }
            });


        }
    } catch (RemoteException ex) {
     } catch (NotBoundException ex) {
     } catch (MalformedURLException ex) {
     }
}                                        

 public void rcvMsg(String msg) {
    final String s = msg;
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            System.out.println("server called");
            System.out.println(s);
            jTextArea1.append(s);
            System.out.println("client msg" + java.awt.EventQueue.isDispatchThread());
            jTextArea1.update(jTextArea1.getGraphics());
        }
    });
}

public static void main(String args[]) {
    try {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new client().setVisible(true);
            }
        });
        client c2 = new client();
        inter stub = (inter) UnicastRemoteObject.exportObject(c2, 0);
        Registry registry = LocateRegistry.createRegistry(1113);
        registry.bind("client2", stub);
    } catch (AlreadyBoundException ex) {
    } catch (AccessException ex) {
    } catch (RemoteException ex) {
    }
}
}

Please help...

A: 

In main after creating c2, call c2.setVisible(true);

The code in rcvMsg is being called on the c2 instance of client. Since the c2 instance is never made visible, you see no change.

You probably want a client to connect to a server, not directly to another client. The client-to-client will work for 2 endpoints. But what happens if you want to add a third? A forth? You really want a server that will act as an intermediary for all the clients.

Devon_C_Miller
+1  A: 

just sharing some information using getGraphics() is not appreciated and can cause problems,

jTextArea1.update(jTextArea1.getGraphics());

and i have also created chat application with RMI:

http://stackoverflow.com/questions/3591162/pass-by-reference-problem-in-rmi there is also client written over there, may be that would be useful for you.

Static Void Main