Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

chat sources

Posted on 1999-06-23
8
Medium Priority
?
292 Views
Last Modified: 2008-03-03
I have a web site hosted at a company, and I want to put a chat function on my web site using Java. Can anyone give me some references or places with source codes? Thanks!
0
Comment
Question by:mscproj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 8

Expert Comment

by:diakov
ID: 1244452
You will need a server side programming as well. I'll look for a link.

Cheers,
  Nik
0
 
LVL 1

Expert Comment

by:sankars98
ID: 1244453

 If you search in the PAQs , you will get the sources
 for a simple Java Chat server and Client.
 I think , 10 days back , some one had asked the
 same question.

 Good Luck,

 Sankar S.
0
 
LVL 1

Expert Comment

by:sankars98
ID: 1244454

 Q. No : 10161259
0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 

Accepted Solution

by:
rodiere earned 150 total points
ID: 1244455
I've written a chat application with RMI technology and an Swing GUI.

you can start the server with the following command :
java ChatServer

and the client with :
java ChatClient <serverHostName>

Here, you'll find the 4 java classes :

***********************************************************
package rmi.chat.client;

/**
 * Fonctions du serveur de discussion
 *
 * @author © 1999 Laurent BARESSE
 * @version 1.0
 */
public interface Chatterer extends java.rmi.Remote  {

/**
 * Invoquée par un client pour entrer dans la discussion de ce serveur.
 *
 * @exception RemoteException si un problème réseau survient...
 */
public void register() throws java.rmi.RemoteException;

/**
 * Invoquée par un client pour sortir de la discussion de ce serveur.
 *
 * @exception RemoteException si un problème réseau survient...
 */
public void unregister() throws java.rmi.RemoteException;

/**
 * Invoquée par un client pour envoyer un message au serveur.
 *
 * @param msg message entre le client et le serveur
 * @exception RemoteException si un problème réseau survient...
 */
public void talk(String msg) throws java.rmi.RemoteException;

}
***********************************************************

package rmi.chat.client;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

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


/**
 * <B>Client RMI pour la discussion</B> <BR>
 * Works as a chat remote object server as well since the chat server relays
 * all messages to all clients.<BR>
 * Fonctionne sur le port RMI par défaut (1099).<BR>
 *
 * @author © 1999 Laurent BARESSE
 * @version 1.0
 */
 
public class ChatClient extends UnicastRemoteObject implements rmi.chat.server.Talker {
      private static final String SERVER_NAME = "Chat Server";
      private static final String NAME = "Chat Client";
      private String URL;
      
      private static ChatClientGUI gui = null;
      
      private static Chatterer obj = null;
      
/**
 * Constructeur
 *
 * @param nom de cet objet distribué dans la registry
 */
public ChatClient(String name) throws RemoteException {
      super();
}

/**
 * Main. <BR>
 * Installe un <CODE>RMISecurityManager</CODE>.<BR>
 * Instancie un client de discussion (ChatClient) et l'enregistre comme
 * objet distribué dans la registry.<BR>
 * Recherche le serveur de discussion dans la registry du serveur et recupére une instance du serveur. <BR>
 * Entre dans la discussion de ce serveur. <BR>
 *
 * @param args argument de la ligne de commande : url de l'hôte du serveur (ex: atchoum.silogic.fr)
 */
public static void main(String[] args) {
    if (System.getSecurityManager() == null)
          System.setSecurityManager(new RMISecurityManager());

      DataInputStream dis = new DataInputStream(System.in);
      ChatClient chatClient;
      String line = "";
      try {
            try {
                  // instaniates and registers an object of this class
                  chatClient = new ChatClient(NAME);

                   Registry registry = LocateRegistry.getRegistry(1099);
               
                try {    
                    registry.rebind(NAME, (rmi.chat.server.Talker) chatClient);
                } catch (Exception ex) {
                    registry = LocateRegistry.createRegistry(1099);  
                    registry.rebind(NAME, (rmi.chat.server.Talker) chatClient);
                }

                  System.out.println(NAME + " bound in registry");

            gui = new ChatClientGUI(chatClient);

                  // looks up and gets a remote chat server object
                  obj = (Chatterer) Naming.lookup("rmi://" + args[0] + "/" + SERVER_NAME);
                  obj.register(); // registers itself with the chat server

      /*
              // handles user input
                  while (line != null) {
                        line = dis.readLine();
                        obj.talk(line); // ships it off to the chat server
                  }
      */
      
      
            } catch (Exception e) {
                  System.err.println("ChatClient exception: " + e.getMessage());
                  e.printStackTrace();
            }
      } catch (Exception e) {
            System.err.println("ChatClient exception: " + e.getMessage());
            e.printStackTrace();
      }
}

/**
 * Invoquée par le serveur pour transmettre tous les messages  à tous les clients. <BR>
 *
 * @param msg message retransmit par le serveur
 * @exception RemoteException si un problème réseau survient...
 */
public void foward(String msg) throws RemoteException {
    if (gui != null) {
        gui.appendMessage(msg);
    }
}


/**
 * Invoquée par le server pour notifier un changement dans la liste des parleurs
 *
 * @param nom Liste des parleurs de la discussion en cours
 * @exception RemoteException si un problème réseau survient...
 */
public void updateTalkersList(String[] nom) throws java.rmi.RemoteException {
    if (gui != null) {
        gui.updateTalkersList(nom);
    }
}

void unregister() {
    try {
        obj.unregister();
    }
    catch (Exception e) { e.printStackTrace(); }
}

void sendMsg(String str) {
    try {    
       if (obj != null) {
           obj.talk(str);
          }
    }
    catch (Exception e) { e.printStackTrace(); }
}    

}

/**
 *  GUI.
 */
class ChatClientGUI extends JFrame {

    private JTextArea text;
    private JTextField tf_saisie;
    private List talkers;
   
    private ChatClient client;
       
    public ChatClientGUI(ChatClient client) {
          
          this.client = client;
          
          setTitle("ChatClient with RMI and Swing");
              
        Container content = getContentPane();
              
          content.setLayout(new GridBagLayout());
          
          content.add(new JLabel("Discussion"),
                      new GridBagConstraints2(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                                            new Insets(5,5,0,5), 0, 0));
          
          text = new JTextArea("");
          text.setEditable(false);
          JScrollPane scroll = new JScrollPane(text);
          content.add(scroll,
                      new GridBagConstraints2(0, 2, 2, 10, 10.0, 20.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
                                            new Insets(5,5,5,5), 0, 0));
              
          tf_saisie = new JTextField();
          tf_saisie.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                doSendMsg(tf_saisie.getText());
                tf_saisie.setText("");
              }
          });
          
          content.add(tf_saisie,
                      new GridBagConstraints2(0, 12, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                                            new Insets(5,5,5,5), 0, 0));
          
          
          JButton btn_Exit = new JButton("Exit");
          btn_Exit.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                doExit();
              }
          });
          
          JPanel btn_panel = new JPanel(new FlowLayout());
          btn_panel.add(btn_Exit);
          content.add(btn_panel,
                      new GridBagConstraints2(0, 13, 3, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
                                            new Insets(5,5,5,5), 0, 0));

          content.add(new JLabel("Talkers"),
                      new GridBagConstraints2(2, 1, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                                            new Insets(5,5,0,5), 0, 0));
                               
        talkers = new List();
        JScrollPane scrollTalker = new JScrollPane(talkers);
          content.add(scrollTalker,
                      new GridBagConstraints2(2, 2, 1, 11, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
                                            new Insets(5,5,5,5), 0, 0));
          
          
          setSize(500,500);
          setVisible(true);
    }
          
      
      private void doSendMsg(String str) {
          try {    
            if (client != null) {
                    client.sendMsg(str);
                }
          }
          catch (Exception e) { e.printStackTrace(); }
    }    
      
      private void doExit() {
        try {
                if (client != null) {
                      client.unregister();
                }
          }
          catch (Exception e) { e.printStackTrace(); }

            System.exit(0);
      }    
      
      
      public void updateTalkersList(String[] nom) {
        talkers.removeAll();
        for (int i=0; i<nom.length; i++)
              talkers.add(nom[i]);
      }
      
      public void appendMessage(String txt) {
          text.append(txt+"\n");  
      }

      /**
       * Une inner class pour les GridBagConstraints
       */
    private class GridBagConstraints2 extends GridBagConstraints {
        public GridBagConstraints2(int gridx, int gridy, int gridwidth, int gridheight,
                             double weightx, double weighty, int anchor, int fill,
                             Insets insets, int ipadx, int ipady) {
       
            this.gridx = gridx;
            this.gridy = gridy;
            this.gridwidth = gridwidth;
            this.gridheight = gridheight;
            this.fill = fill;
            this.ipadx = ipadx;
            this.ipady = ipady;
            this.insets = insets;
            this.anchor  = anchor;
            this.weightx = weightx;
            this.weighty = weighty;
        }
    }

}
***********************************************************

package rmi.chat.server;

/**
 * Fonctionnalités d'un "parleur" (ou ici aussi de retransmetteur de message (serveur))
 *
 * @author © 1999 Laurent BARESSE
 * @version 1.0
 */
public interface Talker extends java.rmi.Remote {
   
/**
 * Invoquée par le server pour retransmettre un message à tous les clients
 *
 * @param msg message entre le client et le serveur
 * @exception RemoteException si un problème réseau survient...
 */
public void foward(String msg) throws java.rmi.RemoteException;

/**
 * Invoquée par le server pour notifier un changement dans la liste des parleurs
 *
 * @param nom Liste des parleurs de la discussion en cours
 * @exception RemoteException si un problème réseau survient...
 */
public void updateTalkersList(String[] nom) throws java.rmi.RemoteException;

}
***********************************************************

package rmi.chat.server;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

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

/**
 * <B>Serveur de discussion RMI rudimentaire</B> <BR>
 * Fonctionne comme client étant donné qu'il transmet tous les messages à tous les clients
 * Fonctionne sur le port RMI par défaut (1099).<BR>
 *
 * @author © 1999 Laurent BARESSE
 * @version 1.0
 */

public class ChatServer extends UnicastRemoteObject implements rmi.chat.client.Chatterer {
      private static final String NAME = "Chat Server";
      private static final String CLIENT_NAME = "Chat Client";
      private Vector chatters;
    private static ChatServerGUI gui;
   
      /**
       * Une inner class pour les clients enregistrés avec ce serveur.
       */
      private class RegisteredChatClient {
            private String url;
            private Talker talkerObj;
            
            /**
             * Constructeur.
             * Récupère et stocke l'objet distribué du client.
             *
             * @param URL de l'hôte du client
             */
            private RegisteredChatClient(String url) {
                  this.url = url;
                  try {
                        talkerObj = (Talker) Naming.lookup("rmi://" + url + "/" + CLIENT_NAME);
                  } catch (Exception e) {
                        System.err.println("Client Registration Exception: " + e.getMessage());
                        e.printStackTrace();
                  }
            }
            
            /**
             * Renvoi l'url de l'hôte du client
             *
             * @return url de l'hôte du client
             */
            private String getURL() {
                  return url;
            }
            
            /**
             * Renvoie l'objet distribué du client
             *
             * @return objet distribué du client
             */
            private Talker getTalker() {
                  return talkerObj;
            }
      }

/**
 * Constructeur
 *
 * @param nom de cet objet distribué dans la registry
 */
public ChatServer(String name) throws RemoteException {
      super();
      chatters = new Vector();
}

/**
 * Main.<BR>
 * Installe un <CODE>RMISecurityManager</CODE>.<BR>
 * Instancie un serveur de discussion (ChatServer) et l'enregistre comme
 * objet distribué dans la registry.<BR>
 *
 * @param args argument de la ligne de commande (non utilisé)
 */
public static void main(String[] args) {
   
    gui = new ChatServerGUI();          
     
    if (System.getSecurityManager() == null)
          System.setSecurityManager(new RMISecurityManager());
   
      try {
            // Instancie et enregistre un objet ChatServer dans la registry
            rmi.chat.client.Chatterer obj = new ChatServer(NAME);
          
            Registry registry = LocateRegistry.getRegistry(1099);
               
            try {    
                registry.bind(NAME, obj);
            } catch (Exception ex) {
                registry = LocateRegistry.createRegistry(1099);  
                registry.bind(NAME, obj);
            }
            
            gui.logText(NAME + " bound in registry");
                        
      } catch (Exception e) {
            gui.logText(NAME + " err: " + e.getMessage());
            e.printStackTrace();
      }
            
}

/**
 * Invoquée par un client pour entrer dans la discussion de ce serveur.<BR>
 *
 * @exception RemoteException si un problème réseau survient...
 */
public void register() throws RemoteException {
      try {
            String clientHost = getClientHost();
            gui.logText("ChatServer registering " + clientHost);
            chatters.addElement(new RegisteredChatClient(clientHost));

          notifyUpdateTalkerList();
            
    } catch (ServerNotActiveException e) {
            gui.logText("ChatServer registration error: " + e.getMessage());
            e.printStackTrace();
      }
}

/**
 * Invoquée par un client. <BR>
 * Retransmet à tous les clients le message du client. <BR>
 *
 * @param msg message du client
 * @exception RemoteException si un problème réseau survient...
 */
public void talk(String msg) throws RemoteException {
      try {
            String clientHost = getClientHost();
            gui.logText(clientHost + ": " + msg);
            
            // relays message to all registered chat clients
            for (int i = 0; i < chatters.size(); i++) {
                  RegisteredChatClient rcc = (RegisteredChatClient) chatters.elementAt(i);
                  gui.logText("Relaying to " + rcc.getURL());
                  rcc.getTalker().foward(clientHost+": "+msg);
            }
      } catch (ServerNotActiveException e) {
            gui.logText("ChatServer error: " + e.getMessage());
            e.printStackTrace();
      }
}

/**
 * Invoquée par un client pour sortir de la discussion de ce serveur.
 *
 * @exception RemoteException si un problème réseau survient...
 */
public void unregister() throws RemoteException {
      try {
            String clientHost = getClientHost();
            for (int i = 0; i < chatters.size(); i++) {
                  RegisteredChatClient rc = (RegisteredChatClient) chatters.elementAt(i);
                  if (clientHost.equals(rc.getURL())) {
                        gui.logText("ChatServer unregistering " + clientHost);
                        chatters.removeElementAt(i);
                  }
            }
            
            notifyUpdateTalkerList();
            
      } catch (ServerNotActiveException e) {
            gui.logText("ChatServer unregistration error :" + e.getMessage());
            e.printStackTrace();
      }      
}

private void notifyUpdateTalkerList() {
    try {
        String[] nom = new String[chatters.size()];
            
            for (int i = 0; i < chatters.size(); i++) {                
                  RegisteredChatClient rcc = (RegisteredChatClient) chatters.elementAt(i);
                  nom[i] = rcc.getURL();
            }

            for (int i = 0; i < chatters.size(); i++) {
                  RegisteredChatClient rcc = (RegisteredChatClient) chatters.elementAt(i);
                  rcc.getTalker().updateTalkersList(nom);
            }

      } catch (RemoteException e) {
            gui.logText("ChatServer error: " + e.getMessage());
            e.printStackTrace();
      }
       
}

}

/**
 *  GUI.
 */
class ChatServerGUI extends JFrame {

    private JTextArea text;
       
    public ChatServerGUI() {
          
          setTitle("ChatServer with RMI and Swing");
              
        Container content = getContentPane();
              
          content.setLayout(new BorderLayout());
          text = new JTextArea("");
          JScrollPane scroll = new JScrollPane(text);
          content.add(scroll,BorderLayout.CENTER);
              
          JButton btn_Exit = new JButton("Exit");
          btn_Exit.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                System.exit(0);
              }
          });
          
          JPanel btn_panel = new JPanel(new FlowLayout());
          btn_panel.add(btn_Exit);
          content.add(btn_panel,BorderLayout.SOUTH);
              
          setSize(500,500);
          setVisible(true);
    }
          
      public void logText(String txt) {
          text.append(txt+"\n");  
      }
}

0
 
LVL 1

Expert Comment

by:sankars98
ID: 1244456

 get the sample code of JavaTalk from the
 following site .It's a Socket Version...

http://www.uk.research.att.com/~fms/javatalk/
0
 

Author Comment

by:mscproj
ID: 1244457
Thanks a lot! But, since the company doesn't permit me to run a java application on their server, so what can I do? Is it possible that there is no server, but the users use the applet on the brower to communication. Basic concept is welcome. Thanks!
0
 

Expert Comment

by:pureDan
ID: 1244458
at www.freecode.com
Take a look and good luck
Dan
0
 

Author Comment

by:mscproj
ID: 1244459
Thanks!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question