Chat application program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • agarwalsrushti
    New Member
    • Feb 2008
    • 63

    Chat application program

    Hi,
    Has anyone ever created a chat application using java. Ive made a one but that works only for 1 to 1 communication between the client and the server. not more than 2 people can communicate with one another.
    Plz help me out its urgent.
  • MarkoKlacar
    Recognized Expert Contributor
    • Aug 2007
    • 296

    #2
    Hi,

    Are you using sockets and serversockets?

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      If you are using Sockets and a ServerSocket as the previous poster asked, let
      the ServerSocket accept a new connection (you'll get a new Socket then) and
      start up a new Thread using that Socket that handles the communication with
      the new client. The first thread simply loops, accepting new connections. The
      newly created Threads handle the client's communication. When the client
      disappears the Thread simply dies.

      If you want to go fancy you can preallocate a fixed 'n' sized pool of client handling
      Threads; if no more Threads are available in that pool you have 'n' clients chatting
      simultaneously. In this simple scenario Threads are waiting in the pool for a new
      client and when the client disappears the Thread doesn't die but returns itself
      to the pool again where it waits until a new client signs on and the cycle repeats.

      kind regards,

      Jos

      Comment

      • agarwalsrushti
        New Member
        • Feb 2008
        • 63

        #4
        Hi,
        Thanks. Im using socket and serversocket only. But i tried a lot it doesnt works. I want that clients should be able to talk to whichever client they want. Im pasting my code for both client and server. Plz check it out and do the changes wherever it is wrong and let me know.

        [code=Java]
        /*
        * Main.java for CLIENT
        *
        * Created on February 16, 2007, 4:24 PM
        */

        import java.net.*;
        import java.io.*;
        import java.awt.*;
        import java.awt.event. *;

        public class Main
        {
        static TextField tf = new TextField();
        static TextArea ta = new TextArea();
        static Button b1 = new Button("SEND");
        static Button b2 = new Button("CLEAR") ;

        public Main()
        {
        }

        public static void main(String[] args)throws Exception
        {
        Frame fr = new Frame();
        Panel p1 = new Panel();

        p1.add(b1);
        p1.add(b2);
        b1.setEnabled(f alse);
        fr.add(p1,Borde rLayout.SOUTH);
        fr.add(ta,Borde rLayout.NORTH);
        fr.add(tf,Borde rLayout.CENTER) ;
        fr.setSize(300, 300);
        fr.setTitle("CL IENT");
        fr.setVisible(t rue);

        InetAddress ip = InetAddress.get ByName("127.0.0 .1");
        Socket soc = new Socket(ip,9090) ;
        System.out.prin tln("CLIENT ON");

        SendData sd1 = new SendData();
        sd1.SetSoc(soc) ;
        b1.addActionLis tener(sd1);
        System.out.prin tln("CLIENT CONNECTION ESTABLISHED");

        TClient t = new TClient();
        t.SetSoc(soc);
        t.start();

        WindowCheck wc1 = new WindowCheck();
        fr.addWindowLis tener(wc1);

        Clear cl = new Clear();
        b2.addActionLis tener(cl);

        Datatyped b = new Datatyped();
        tf.addKeyListen er(b);

        //soc.close();
        }
        }


        /*
        * SendData.java , Class for ActionListener for Send button in CLIENT
        *
        * Created on February 16, 2007, 12:54 PM
        */

        class SendData implements ActionListener
        {
        private Socket soc;
        private PrintWriter out;
        String str = new String();

        public SendData()
        {
        }

        public void actionPerformed (ActionEvent e)
        {
        try
        {
        OutputStream i = soc.getOutputSt ream();
        OutputStreamWri ter j = new OutputStreamWri ter(i);
        BufferedWriter k = new BufferedWriter( j);
        PrintWriter out = new PrintWriter(k,t rue);

        str =Main.tf.getTex t();
        Main.ta.append( "CLIENT:" + str + "\n");
        Main.tf.setText ("");

        System.out.prin tln("CLIENT:" + str);
        out.println(str );
        }

        catch (IOException ex)
        {
        ex.printStackTr ace();
        }
        }

        public void SetSoc(Socket soc) throws Exception
        {
        this.soc = soc;
        }
        }


        /*
        * TClient.java for CLIENT
        *
        * Created on February 16, 2007, 4:24 PM
        */

        class TClient extends Thread
        {

        private Socket soc; //Cannot be made static else each
        private BufferedReader in; //Client will not get separate socket

        public TClient()
        {
        }

        public void run()
        {
        try
        {
        BufferedReader in = new BufferedReader(
        new InputStreamRead er(
        soc.getInputStr eam()));


        String Str = in.readLine();
        while(true)
        {
        System.out.prin tln(" FROM SERVER : " + Str);
        Main.ta.append( "SERVER : " + Str + "\n");
        Str = in.readLine();
        }

        }

        catch (IOException ex)
        {
        ex.printStackTr ace();
        }
        }

        public void SetSoc(Socket soc) throws Exception
        {
        this.soc = soc;
        }

        }


        /*
        * Datatyped.java for CLIENT
        *
        * Created on February 15, 2007, 11:25 PM
        */

        class Datatyped implements KeyListener
        {

        public void keyTyped(KeyEve nt e)
        {

        }

        public void keyPressed(KeyE vent e)
        {
        Main.b1.setEnab led(true);
        }

        public void keyReleased(Key Event e)
        {
        }

        }


        /*
        * Clear.java , Class for ActionListener for Clear button in CLIENT
        *
        * Created on February 20, 2007, 9:32 AM
        */

        class Clear implements ActionListener
        {
        public Clear()
        {
        }

        public void actionPerformed (ActionEvent e)
        {
        Main.ta.setText ("");
        }
        }


        /*
        * WindowCheck.jav a for CLIENT
        *
        * Created on February 16, 2007, 12:31 PM
        */

        class WindowCheck implements WindowListener
        {

        public WindowCheck()
        {
        }

        public void windowOpened(Wi ndowEvent e)
        {
        }

        public void windowClosing(W indowEvent e)
        {
        System.exit(0);
        }

        public void windowClosed(Wi ndowEvent e)
        {
        }

        public void windowIconified (WindowEvent e)
        {
        }

        public void windowDeiconifi ed(WindowEvent e)
        {
        }

        public void windowActivated (WindowEvent e)
        {
        }

        public void windowDeactivat ed(WindowEvent e)
        {
        }

        }
        [/code]

        code for server
        [code=Java]
        /*
        * Main.java for SERVER
        *
        * Created on February 16, 2007, 4:24 PM
        */

        import java.net.*;
        import java.io.*;
        import java.awt.*;
        import java.awt.event. *;

        public class Main
        {
        static TextField tf = new TextField();
        static TextArea ta = new TextArea();
        static Button b1 = new Button("SEND");
        static Button b2 = new Button("CLEAR") ;

        public Main()
        {
        }

        public static void main(String[] args) throws Exception
        {
        Frame fr = new Frame();
        Panel p1 = new Panel();

        p1.add(b1);
        p1.add(b2);
        b1.setEnabled(f alse);
        fr.add(p1,Borde rLayout.SOUTH);
        fr.add(ta,Borde rLayout.NORTH);
        fr.add(tf,Borde rLayout.CENTER) ;
        fr.setSize(500, 300);
        fr.setTitle("SE RVER");
        fr.setVisible(t rue);

        System.out.prin tln("SERVER ON");
        InetAddress ip = InetAddress.get ByName("127.0.0 .1");
        ServerSocket ss = new ServerSocket(90 90);
        Socket soc = ss.accept();

        TServer t1 = new TServer();
        t1.SetSoc(soc);
        t1.start();
        System.out.prin tln("CLIENT CONNECTED TO SERVER ");

        SendData ssd = new SendData();
        ssd.SetSoc(soc) ;
        b1.addActionLis tener(ssd);

        Clear cl = new Clear();
        b2.addActionLis tener(cl);

        WindowCheck wc1 = new WindowCheck();
        fr.addWindowLis tener(wc1);

        Datatyped b = new Datatyped();
        tf.addKeyListen er(b);
        // soc.close();
        // ss.close();
        }
        }


        /*
        * SendData.java for SERVER
        *
        * Created on February 16, 2007, 4:24 PM
        */

        class SendData implements ActionListener
        {
        private Socket soc;
        private PrintWriter out;
        String str = new String();

        public SendData()
        {
        }

        public void actionPerformed (ActionEvent e)
        {
        try
        {
        OutputStream i = soc.getOutputSt ream();
        OutputStreamWri ter j = new OutputStreamWri ter(i);
        BufferedWriter k = new BufferedWriter( j);
        PrintWriter out = new PrintWriter(k,t rue);

        str =Main.tf.getTex t();
        Main.ta.append( "SERVER:" + str + "\n");
        Main.tf.setText ("");

        System.out.prin tln("SERVER:" + str);
        out.println(str );

        }

        catch (IOException ex)
        {
        ex.printStackTr ace();
        }

        }

        public void SetSoc(Socket soc) throws Exception
        {
        this.soc = soc;
        }
        }


        /*
        * TServer.java for SERVER
        *
        * Created on February 16, 2007, 4:24 PM
        */

        class TServer extends Thread
        {
        private Socket soc; //Cannot be made static else each
        private PrintWriter out; //client will not get separate socket
        private BufferedReader in;

        public TServer() throws Exception
        {

        }

        public void run()
        {
        try
        {

        BufferedReader in = new BufferedReader(
        new InputStreamRead er(
        soc.getInputStr eam()));

        PrintWriter out = new PrintWriter(
        new BufferedWriter(
        new OutputStreamWri ter(
        soc.getOutputSt ream())),true);

        String Str = in.readLine();
        while(true)
        {
        System.out.prin tln(" FROM CLIENT : " + Str);
        Main.ta.append( "CLIENT : " + Str + "\n");
        Str = in.readLine();
        }
        }
        catch (Exception ex)
        {
        ex.printStackTr ace();
        }
        }

        public void SetSoc(Socket soc) throws Exception
        {
        System.out.prin tln("CLIENT SOCKET CONNECTED");
        this.soc = soc;
        }
        }


        /*
        * Datatyped.java for SERVER
        *
        * Created on February 15, 2007, 11:25 PM
        */

        class Datatyped implements KeyListener
        {

        public void keyTyped(KeyEve nt e)
        {

        }

        public void keyPressed(KeyE vent e)
        {
        Main.b1.setEnab led(true);
        }

        public void keyReleased(Key Event e)
        {
        }

        }


        /*
        * Clear.java , Class for ActionListener for Clear button in SERVER
        *
        * Created on February 20, 2007, 9:23 AM
        */

        class Clear implements ActionListener
        {
        public Clear()
        {
        }

        public void actionPerformed (ActionEvent e)
        {
        Main.ta.setText ("");
        }
        }


        /*
        * WindowCheck.jav a for SERVER
        *
        * Created on February 16, 2007, 4:24 PM
        */

        class WindowCheck implements WindowListener
        {

        public WindowCheck()
        {
        }

        public void windowOpened(Wi ndowEvent e)
        {
        }

        public void windowClosing(W indowEvent e)
        {
        System.exit(0);
        }

        public void windowClosed(Wi ndowEvent e)
        {
        }

        public void windowIconified (WindowEvent e)
        {
        }

        public void windowDeiconifi ed(WindowEvent e)
        {
        }

        public void windowActivated (WindowEvent e)
        {
        }

        public void windowDeactivat ed(WindowEvent e)
        {
        }

        }

        [/code]


        Plz helpme out. Thanks again

        Comment

        • chaarmann
          Recognized Expert Contributor
          • Nov 2007
          • 785

          #5
          Originally posted by agarwalsrushti
          Hi,
          Has anyone ever created a chat application using java. Ive made a one but that works only for 1 to 1 communication between the client and the server. not more than 2 people can communicate with one another.
          Plz help me out its urgent.
          I created one recently, which works with AJAX in a browser.
          Are you using more than one server or more than one JVM on one server?
          If yes, you need to synchronize the messages from users on different JVMs through an EJB (or the slower way: through a database) or write something of your own with Sockets or RMI.
          If no, you can just save the messages altogether in a hashmap which is declared static.

          If you use sockets, you should have one message-server where all clients connect to. So clients are not connected between each other, but connect to the same message server. Then clients can add messages to the server, or they poll the server for new messages.
          Clients are storing the last message number they got. So they will only get newer messages (=messages with higer number) when they call code like
          Code:
          void poll()
          {
             Messages newMessages = server.getNewMessages(messageNumber);
             display(newMessages);
             messageNumber += newMessages.getSize();
          }
          You might think of programming that the server keeps track of each last message sent over to each client, but that will create much more work for you, because then you have to care for cleanup of disconnected clients etc.

          Comment

          Working...