Creating the Chat Client


To create the chat client, you need to create the following files:

  • ChatLogin.java file

  • ChatClient.java file

  • CClient.java file

  • Messager.java file

Creating ChatLogin.java File

The ChatLogin.java file helps create a login window. In the login window, an end user enters the server IP address, user name , and password to connect to the chat server.

Listing 2-7 shows the contents of the ChatLogin.java file:

Listing 2-7: The ChatLogin.java File
start example
 /* Imports the javax.swing package classes. */ import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JDialog; import javax.swing.JPasswordField; import javax.swing.BorderFactory; /*Imports the java.awt package classes.*/ import java.awt.GraphicsEnvironment; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.FlowLayout; import java.awt.Font; /*Imports the javax.swing.event package classes.*/ import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.JSeparator; /*  class ChatLogin - Creates the Chat Login window for the chat application.       Method:       - actionPerformed()       - main() */ public class ChatLogin extends JDialog implements ActionListener {    JPanel panel;    JPanel pane;    /* Declares the objects of the JLabel class. */    JLabel titleLabel;    JLabel nameLabel;    JLabel pwdLabel;    JLabel ipLabel;    /* Declares the objects of JTextField class */    JTextField nameText;    JPasswordField pwdText;    JTextField ipText;       /*Declares the objects of the JButton class.*/    JButton connect;    JButton cancel;    GridBagLayout gbl;    GridBagConstraints gbc;    int value;    /* Defines the default constructor.*/    public ChatLogin()    {       /*Sets the title of the Font dialog box.*/       setTitle("Chat Login Window");       /*Sets the size of Font dialog box.*/       setSize(280, 170);       /*Sets resizable button to FALSE.*/       setResizable(false);       /*Initializes the object of the GridBagLayout class*/       gbl = new GridBagLayout();       /* Sets the Layout. */       getContentPane().setLayout(gbl);       /*Creates an object of the GridBagConstraints class.*/       gbc = new GridBagConstraints();       /*           Initializes the title label object and adds it to the 1, 1, 2, 1 position with WEST          alignment.        */          gbc.gridx = 1;             gbc.gridy = 1;          gbc.gridwidth = 2;          gbc.gridheight = 1;          gbc.anchor = GridBagConstraints.CENTER;          pane = new JPanel();       pane.setLayout(new FlowLayout());       titleLabel = new JLabel("Chat Login Window");       titleLabel.setFont(new Font("Verdana",Font.BOLD,20));       pane.add(titleLabel);       getContentPane().add(pane, gbc);       gbc.gridx = 1;          gbc.gridy = 2;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       getContentPane().add(new JSeparator(), gbc);       /*           Initializes the IP address label object and adds it to the 1, 3, 1, 1 position with          EAST alignment        */          gbc.gridx = 1;          gbc.gridy = 3;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.EAST;       ipLabel = new JLabel("Server IP: ");       getContentPane().add(ipLabel, gbc);       /*  Initializes the IP address text field object and adds it to the 2, 3, 1, 1 position with WEST alignment        */       gbc.gridx = 2;          gbc.gridy = 3;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       ipText = new JTextField("192.168.0.36", 15);       ipText.setFont(new Font("Verdana",Font.PLAIN,12));       getContentPane().add(ipText, gbc);       gbc.gridx = 1;          gbc.gridy = 4;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       getContentPane().add(new JSeparator(), gbc);       /*  Initializes the user name label object and adds it to the 1, 5, 1, 1 position with EAST alignment.        */          gbc.gridx = 1;          gbc.gridy = 5;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.EAST;       nameLabel = new JLabel("User Name: ");       getContentPane().add(nameLabel, gbc);       /*           Initializes the user name text field object and adds it to the 2, 5, 1, 1 position with          WEST alignment.        */       gbc.gridx = 2;          gbc.gridy = 5;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       nameText = new JTextField(15);       nameText.setFont(new Font("Verdana",Font.PLAIN,12));       getContentPane().add(nameText, gbc);       gbc.gridx = 1;          gbc.gridy = 6;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       getContentPane().add(new JSeparator(), gbc);       /*           Initializes the password label object and adds it to the 1, 7, 1, 1 position with EAST          alignment.        */          gbc.gridx = 1;          gbc.gridy = 7;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.EAST;       pwdLabel = new JLabel("Password: ");       getContentPane().add(pwdLabel, gbc);       /*           Initializes the password text field object and adds it to the 2, 7, 1, 1 position with          WEST alignment.        */       gbc.gridx = 2;          gbc.gridy = 7;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       pwdText = new JPasswordField(15);       pwdText.setFont(new Font("Verdana",Font.PLAIN,12));       pwdText.addActionListener(this);       getContentPane().add(pwdText, gbc);       gbc.gridx = 1;          gbc.gridy = 8;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       getContentPane().add(new JSeparator(), gbc);       /*           Initializes the OK and Cancel button. Adds the button to the 2, 9, 1, 1 position with          WEST alignment.        */       gbc.gridx = 2;          gbc.gridy = 9;       gbc.gridwidth = 1;       gbc.gridheight = 1;       gbc.anchor = GridBagConstraints.WEST;       panel = new JPanel();       panel.setLayout(new FlowLayout(FlowLayout.LEFT));       connect = new JButton("Connect");       connect.addActionListener(this);       cancel = new JButton("Cancel");       cancel.addActionListener(this);       panel.add(connect);       panel.add(cancel);       getContentPane().add(panel, gbc);       addWindowListener(new WindowAdapter()       {          public void windowClosing(WindowEvent we)          {             System.exit(0);          }       });       }    /* actionPerformed() - This method is called when the user clicks the any button. Parameters: ae: Represents an object of the ActionEvent class that contains the details of the event.    Return Value: NA    */    public void actionPerformed(ActionEvent ae)    {       if(ae.getSource() == connect)       { /*Creates an object of the ChatClient class.*/          ChatClient tcc = new ChatClient(); /*Calls the con() method to connect to the server.*/ tcc.con(nameText.getText(), pwdText.getText(), ipText.getText());          this.setVisible(false);                      }       else if(ae.getSource() == cancel)       {          System.exit(0);       }       else if(ae.getSource() == pwdText)       {          /*Creates an object of the ChatClient class.*/          ChatClient tcc = new ChatClient();          /*Calls the con() method to connect to the server.*/          tcc.con(nameText.getText(), pwdText.getText(), ipText.getText());          this.setVisible(false);                         }          }          /*Main method.*/             public static void main(String args[])          {             try             {                /*Sets the window look and feel to the application.*/                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");             }             catch(Exception e){}                   ChatLogin cl = new ChatLogin();             cl.show();       } } 
end example
 

Download this Listing .

In the above code, the main() method creates an instance of the ChatLogin class that allows you to open the Chat Login window, as shown in Figure 2-2:

this figure shows the chat login window for the chat application. it provides three text boxes, server ip, user name, and password, and two buttons, connect and cancel.
Figure 2-2: The Chat Login Window

After an end user specifies the server IP address, user name, and password and clicks any button on the Chat Login window, the chat application invokes the actionPerformed() method. This method acts as an event listener and activates an appropriate class and method, based on the button the end user clicks. If the end user clicks the Connect button or presses the Enter key, the actionPerformed() method creates an object of the ChatClient class and calls the con() method of the ChatClient class.

Creating ChatClient.java File

The ChatClient.java file helps create a user interface for the chat client. End users can use this interface to display the user list of the connected users. The chat application user interface contains a text pane that displays the messages sent by other chat users.

Listing 2-8 shows the contents of the ChatClient.java file:

Listing 2-8: The ChatClient.java File
start example
 /*Imports the java.awt package classes.*/ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.List; import java.awt.Point; /*Imports the java.awt.event package classes.*/ import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /*Imports java.io package classes.*/ import java.io.PrintStream; /*Imports java.util package classes.*/ import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; /*Imports the javax.swing package classes.*/ import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JOptionPane; import javax.swing.UIManager; /*Imports the java.swing.text package classes.*/ import javax.swing.text.AttributeSet; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; /* Class ChatClient - Creates the main window of the chat application. This window contains a text pane to display the messages and list box to display the user list.    Methods:       - prepareAllStyles()       - run()       - itemStateChanged()       - actionPerformed()       - con()       - AddUser()    Class       - ListofUser       - PrivateChat       - BroadcastChat */ public class ChatClient extends JFrame implements ActionListener, Runnable, ItemListener {    /*Declares the AWT and Swing components.*/    JPanel paneMain;    JPanel paneLeft;    JPanel paneRight;    JPanel paneBottom;    JLabel welcomeLabel;    JLabel listLabel;    JLabel pMsgLabel;    JLabel bMsgLabel;    JTextField msgText;    JTextArea pArea;    JTextField empty;    List clientList;    JScrollPane pAreaScroll;    JScrollPane listScroll;    JButton sendButton;       JButton privateButton;    JButton logoutButton;    JTextField listText;    SimpleAttributeSet aset;    AttributeSet current;    Hashtable ht = null;    DefaultStyledDocument doc = null;    JTextPane tp = null;    /*Declares the object of the Thread class.*/    Thread thread;    Thread t;    Thread th;    /*Declares the static string to set the text pane attributes.*/    final String NORMALBLUE = "NormalBlue";    final String BOLDBLUE = "BoldBlue";    final String NORMALBLACK = "NormalBlack";    final String BOLDGREEN = "BoldGreen";    final String NORMALRED = "NormalRed";    final String ITALICRED = "ItalicRed";    /*Declares the objects of the String class.*/    String nameStr1 = null;    String msgStr1 = null;    String nameStr2 = null;    String msgStr2 = null;    String str3 = null;    String str4 = null;    String str5 = null;    String str6 = null;    String msg;    String user;    int value;    int count=0;    int i;    /*Creates the object of the PrivateChat class.*/    PrivateChat Pchat = new PrivateChat();    /*Creates the object of the BroadcastChat class.*/    BroadcastChat Achat = new BroadcastChat();    /*Creates the object of the ListofUser class.*/    ListofUser UL=new ListofUser();    /*Creates the object of the CClient class.*/    CClient CC = null;    /*Defines the default constructor.*/    public ChatClient()    {       setSize(700, 400);       setTitle("Chat Client");       setResizable(false);       paneMain = new JPanel();       paneMain.setLayout(new BorderLayout());       getContentPane().add(paneMain);       paneLeft = new JPanel();       paneLeft.setLayout(new BorderLayout());       doc = new DefaultStyledDocument();       ht = new Hashtable();       tp = new JTextPane(doc)       {          public void paintComponent(Graphics g)          {          super.paintComponent(g);          }          public void paint(Graphics g)          {             super.paint(g);          }       };       tp.setFont(new Font("Verdana", Font.PLAIN, 12));       tp.setEditable(false);       pAreaScroll = new JScrollPane(tp);       paneLeft.add(pAreaScroll, BorderLayout.CENTER);       paneMain.add(paneLeft, BorderLayout.CENTER);       paneRight = new JPanel();       paneRight.setLayout(new BorderLayout());       listLabel = new JLabel("User List");       listText = new JTextField(10);       listText.setVisible(false);       clientList = new List(3);       clientList.addActionListener(this);       clientList.addItemListener(this);       clientList.select(0);       listScroll = new JScrollPane(clientList);       paneRight.add(listText, BorderLayout.SOUTH);       paneRight.add(listLabel, BorderLayout.NORTH);       paneRight.add(listScroll, BorderLayout.CENTER);       paneMain.add(paneRight, BorderLayout.EAST);       paneBottom = new JPanel();       paneBottom.setLayout(new FlowLayout());       msgText = new JTextField(33);       msgText.requestFocus();       msgText.addActionListener(this);       msgText.setFont(new Font("Verdana",Font.PLAIN,14));       sendButton = new JButton("Send");       privateButton = new JButton("Private Message");       logoutButton = new JButton("Logout");       empty = new JTextField(10);       paneBottom.add(msgText);       paneBottom.add(sendButton);       paneBottom.add(privateButton);       paneBottom.add(logoutButton);       paneBottom.add(empty);       paneMain.add(paneBottom, BorderLayout.SOUTH);       privateButton.addActionListener(this);       sendButton.addActionListener(this);       logoutButton.addActionListener(this);       prepareAllStyles();       t = new Thread(this);        /*          addWindowListener - It contains a windowClosing() method.          windowClosing: It is called when the user clicks the cancel button of the Window. It _          closes the main window.             Parameter: we- Object of WindowEvent class.             Return Value: NA       */       addWindowListener(new WindowAdapter()       {          public void windowClosing(WindowEvent we)          {             value = JOptionPane.showConfirmDialog(null, "Are you sure you want to close the chat             application?", "Close", JOptionPane.YES_NO_OPTION);             if(value == 0)             {                try                {                   /*Calls the sendBroadMsg() method to inform all the users.*/                   CC.sendBroadMsg(user + "* has left the chat session." + "+REMOVE");                   System.exit(0);                }                catch(Exception e){}             }             else if(value == 1)             {                      }                                  }                    });       } /*Defines the prepareAllStyles() method that set the text attribute values.*/ public void prepareAllStyles()    {             aset = new SimpleAttributeSet();       StyleConstants.setForeground(aset,Color.blue);       StyleConstants.setFontSize(aset,12);       StyleConstants.setFontFamily(aset,"Verdana");       ht.put(NORMALBLUE,aset);       aset = new SimpleAttributeSet();       StyleConstants.setForeground(aset,Color.blue);       StyleConstants.setFontSize(aset,12);       StyleConstants.setFontFamily(aset,"Verdana");       StyleConstants.setBold(aset, true);       ht.put(BOLDBLUE,aset);          aset = new SimpleAttributeSet();          StyleConstants.setForeground(aset,Color.black);         StyleConstants.setFontSize(aset,12);       StyleConstants.setFontFamily(aset,"Verdana");       ht.put(NORMALBLACK,aset);          aset = new SimpleAttributeSet();          StyleConstants.setForeground(aset, new Color(0, 128, 0));         StyleConstants.setFontSize(aset,12);       StyleConstants.setFontFamily(aset,"Verdana");       StyleConstants.setBold(aset, true);       ht.put(BOLDGREEN,aset);             aset = new SimpleAttributeSet();          StyleConstants.setForeground(aset,Color.red);         StyleConstants.setFontSize(aset,12);       StyleConstants.setFontFamily(aset,"Verdana");       ht.put(NORMALRED,aset);       aset = new SimpleAttributeSet();          StyleConstants.setForeground(aset,Color.red);         StyleConstants.setFontSize(aset,12);       StyleConstants.setFontFamily(aset,"Verdana");       StyleConstants.setItalic(aset, true);       ht.put(ITALICRED,aset);          }    /* itemStateChanged() - This method is called when the end user selects the user name from the user list.    Parameters: ae: Represent an object of the ActionEvent class that contains the details of the event.       Return Value: NA    */       public void itemStateChanged(ItemEvent ie)     {       if(ie.getSource() == clientList)       { listText.setText(clientList.getSelectedItem());          i = clientList.getSelectedIndex();                }    }    /*       actionPerformed() - This method is called when the end user clicks any button.          Parameters: ae: Represent an object of the ActionEvent class that contains the details       of the event.       Return Value: NA    */       public void actionPerformed(ActionEvent ae)    {       /*           This section is executed when the end user clicks the Private Message button of the application.         */          if(ae.getSource() == privateButton)       {          try          { if(listText.getText().equals("*" + user))             {                JOptionPane.showMessageDialog(null, "You cannot send private message to _                yourself!", "Error",                JOptionPane.ERROR_MESSAGE);             }             else             {                current = (AttributeSet)ht.get(BOLDBLUE);                doc.insertString(doc.getLength(), "To " + listText.getText() + ": " ,current);                current = (AttributeSet)ht.get(NORMALBLACK);                doc.insertString(doc.getLength(), msgText.getText() +  "\n" ,current);                Point pt1=tp.getLocation();                Point pt2=new Point((int)(0),(int)(tp.getBounds().getHeight()));                pAreaScroll.getViewport().setViewPosition(pt2);             }          } catch(Exception e) {} if(msgText.getText().trim().equals(""))          {                      }          else          {             /*Calls the sendPrivateMessage() method to send the private message.*/              CC.sendPrivateMessage(msgText.getText().trim(),listText.getText());             msgText.setText("");          }                }       /*  This section is executed, when the end user clicks the Send button of the application.         */          else if(ae.getSource() == sendButton)       {          if(msgText.getText().trim().equals(""))          {                      }          else          {             /*Calls the sendBroadMsg() method to send the broadcast message.*/              CC.sendBroadMsg(msgText.getText().trim() + "+MSG");             msgText.setText("");                      }                }       /*  This section is executed, when the end user clicks the Logout button of the application.         */          else if(ae.getSource() == logoutButton)       {          value = JOptionPane.showConfirmDialog(null, "Are you sure you want to logout?", "Logout",          JOptionPane.YES_NO_OPTION);          if(value == 0)          {          try          {          /*Calls the sendBroadMsg() method to inform the end user has left the chat session.*/           CC.sendBroadMsg(user + "* has left the chat session." + "+REMOVE");          System.exit(0);             }             catch(Exception e){}          }          else if(value == 1)          {                   }       }       /*  This section is executed, when the end user enter the sending text and press the enter button from the keyboard.         */          else if(ae.getSource() == msgText)       { /*Calls the sendBroadMsg() method to send the broadcast message.*/   CC.sendBroadMsg(msgText.getText().trim() + "+MSG");          msgText.setText("");                }    } /*Implementation of con() method. This method establishes the connection between client and server.*/ public void con(String userName, String pwd, String ipAdd)    {       user = userName;       CC = new CClient();       /*Calls the addMessager() method of the CClient class.*/       CC.addMessager(UL , Achat, Pchat);       try       {          /*Calls the connect() method of the CClient class.*/          CC.connect(userName, pwd, ipAdd);       }       catch(Exception e)       {          JOptionPane.showMessageDialog(null, "Unable to connect the server!", "Error",          JOptionPane.ERROR_MESSAGE);           ChatLogin cl = new ChatLogin();          cl.show();          this.setVisible(false);          return;       } setTitle("Chat Application - " + userName); /*Starts the thread to send to inform all the users.*/       try       {          count = 1;          t = new Thread(this);          t.setPriority(Thread.MAX_PRIORITY);          t.sleep(100);          t.start();                            }       catch(Exception e){};          /*Starts the thread to display the user list.*/       try       {          count = 2;          thread = new Thread(this);          thread.sleep(100);          thread.start();                }       catch(Exception e){}             this.show();                         tp.repaint();    } /*Creates the class to display the user list.*/    class ListofUser implements Messager    {       public void message(String m)       {          clientList.clear();          AddUser(m);          clientList.select(i);                 }    }; /*Creates the class to send the private message.*/ class PrivateChat implements Messager    {       public void message(String m)       {          try          {             /*Inserts text in the text pane with the specified attributes.*/             m=m.substring(0,m.length()-1);             StringTokenizer st1 = new StringTokenizer(m, ":");             nameStr1 = st1.nextToken();             msgStr1 = st1.nextToken();             current = (AttributeSet)ht.get(BOLDBLUE);             doc.insertString(doc.getLength(), "From " + nameStr1 + ": ", current);             current = (AttributeSet)ht.get(NORMALBLACK);             doc.insertString(doc.getLength(), msgStr1 + "\n" , current);             Point pt1=tp.getLocation();             Point pt2=new Point((int)(0),(int)(tp.getBounds().getHeight()));             pAreaScroll.getViewport().setViewPosition(pt2);          }          catch(Exception e){}          tp.repaint();       }    }; /*Creates the class to send the broadcast message.*/    class BroadcastChat implements Messager    {       public void message(String m)       {          try          {             /*Inserts text in the text pane with the specified attributes.*/             StringTokenizer st2 = new StringTokenizer(m, ":");             nameStr2 = st2.nextToken();             msgStr2 = st2.nextToken();             StringTokenizer st3 = new StringTokenizer(msgStr2, "+");             str3 = st3.nextToken();             str4 = st3.nextToken();             if(str4.equals("ADD"))             {                StringTokenizer st4 = new StringTokenizer(str3, "*");                str5 = st4.nextToken();                str6 = st4.nextToken();                if(str5.equals(user))                {                   try                {                   msg = "Welcome to chat session!";                   current = (AttributeSet)ht.get(BOLDBLUE);                   tp.setCharacterAttributes(current,true);                   doc.insertString(doc.getLength(),  msg + "\n",current);                }                catch(Exception e){}                }                else                {                   try                   {                      current = (AttributeSet)ht.get(ITALICRED);                      doc.insertString(doc.getLength(), str5 + str6 + "\n",current);                      Point pt1=tp.getLocation();                      Point pt2=new Point((int)(0),(int)(tp.getBounds().getHeight()));                      pAreaScroll.getViewport().setViewPosition(pt2);                   }                catch(Exception e){}                }             } else if(str4.equals("REMOVE"))             {                StringTokenizer st4 = new StringTokenizer(str3, "*");                str5 = st4.nextToken();                str6 = st4.nextToken();                if(str5.equals(user))                {                   try                   {                      msg = "You have successfully logged out from this chat session.";                      current = (AttributeSet)ht.get(ITALICRED);                      doc.insertString(doc.getLength(), msg + "\n",current);                      Point pt1=tp.getLocation();                      Point pt2=new Point((int)(0),(int)(tp.getBounds().getHeight()));                      pAreaScroll.getViewport().setViewPosition(pt2);                   }                catch(Exception e){}                }                else                {                   try                   {                      current = (AttributeSet)ht.get(ITALICRED);                      doc.insertString(doc.getLength(), str5 + str6 + "\n",current);                      Point pt1=tp.getLocation();                      Point pt2=new Point((int)(0),(int)(tp.getBounds().getHeight()));                      pAreaScroll.getViewport().setViewPosition(pt2);                   }                catch(Exception e){}                }             }             else if (str4.equals("MSG"))             {                try                {                   current = (AttributeSet)ht.get(BOLDGREEN);                   doc.insertString(doc.getLength(), nameStr2 + ": " , current);                   current = (AttributeSet)ht.get(NORMALBLUE);                   doc.insertString(doc.getLength(), str3 + "\n",current);                   Point pt1=tp.getLocation();                   Point pt2=new Point((int)(0),(int)(tp.getBounds().getHeight()));                   pAreaScroll.getViewport().setViewPosition(pt2);                }                catch(Exception e){}             }          }          catch (Exception ex) {}          tp.repaint();       }    }; /*Creates the class to add a new end user into the user list.*/ private void AddUser(String s)    {       String tmp="";       byte b[]=s.getBytes();       if(s.length()>1)        {          for(int x=1;x<b.length;x++)          {             if(b[x]==31)             {                      if(tmp.equals(user))                {                   clientList.add("*"+tmp);                }                else                {                   clientList.add(tmp);                               }                tmp="";             }             else              tmp+=(char)b[x];           }       }    }; /*This method is invoked when thread is started.*/ public void run()    {       if(count == 1)       {          /*Calls the sendBroadMsg() to inform all the end users.*/          CC.sendBroadMsg(user + "* has joined the chat session." + "+ADD");       }       else if(count == 2)       {          while(true)          {             try             {                /*Calls the sendListMsg() method to display the list of users.*/                CC.sendListMsg("");                Thread.sleep(5000);                            } catch(Exception ee){ee.printStackTrace();}          }       }          } } 
end example
 

Download this Listing .

In the above code, the constructor of the ChatClient class creates the user interface for the chat client window, as shown in Figure 2-3:

click to expand: this figure shows the chat client window that has a text pane in the left and a user list pane in the right. the bottom pane consists of a message sending text box and three buttons, send, private message, and logout.
Figure 2-3: The Chat Client Window

The text pane displays the messages the end users send or receive. The user interface allows an end user to send private and broadcast messages to other end users connected with the chat server. To send a public or broadcast message to all the users, the end user needs to type the message in the text box in the bottom pane and click the Send button. To send a private message to a particular chat client, the end user needs to select the client s user name from the user list, type the message in the text box, and click the Private Message button.

The inner classes defined in the above code are:

  • ListofUser : Implements the Messager interface and defines the abstract method, message(). The message() method calls the clear() method to clear the user list and the AddUser() method to add the end user.

  • PrivateChat : Implements the Messager interface and defines the abstract method, message(). The message() method tokenizes the message to retrieve the user name and the message. The message() method then sets the attributes of the document and calls the insertString() method to insert the message in the text pane.

  • BroadcastChat : Implements the Messager interface and defines the abstract method, message(). The message() method tokenizes the message to retrieve the user name and the message. Next , the message() method again tokenizes the message to check the message type, such as new end user connected message, user left message, or simple broadcast message. The message() method then sets the attributes of the document and calls the insertString() method to insert the message in the text pane.

The methods defined in the above code are:

  • con() : Accepts the user name, password, and IP address and calls the addMessager() method of the CClient class. The con() method also calls the connect() method of the CClient class to connect the end user to the chat server.

  • run() : Checks the value of the variable count. If the count value is 1, this method calls the sendBroadMsg() method of the CClient class to send a message to all the users that a new end user has joined the chat session. If the count value is 2, the run() method calls the sendListMsg() method of the CClient class to display the user list.

  • prepareAllStyles() : Sets the text attribute values. This method initializes the object of the SimpleAttributeSet class and calls the setForeground(), setFontSize(), setFontFamily(), setBold(), and setItalic() methods of the StyleConstants class to set the document styles.

  • actionPerformed() : Acts as an event listener and activates an appropriate class or method, based on the button the end user clicks on the Chat Client window. If the end user clicks the Send button of the Chat application, the actionPerformed() method calls the sendBroadMsg() method to send the message to all the users connected to the chat server. If the end user clicks the Private Message button of the Chat application, the actionPerformed() method calls the sendPrivateMessage() method to send the message to a specified chat user. If an end user clicks the Logout button of the Chat application, the actionPerformed() method calls the sendBroadMsg() method to send a message to all the users that this end user has left the chat session. The actionPerformed() method then calls the System.exit(0) method to close the Chat application window.

  • itemStateChanged() : Acts as an event listener and activates an appropriate method, based on the item the end user selects from the user list box.

  • AddUser() : Adds the user to the user list. This method separates the user name from the message sent by the chat server to chat client.

Creating CClient.java File

The CClient.java file implements the core functionality of the chat client module. This file reads the server IP address, user name, and password from the Chat Login window and connects the end user to the chat server. An end user can use this file to send and receive messages from the chat server.

Listing 2-9 shows the contents of the CClient.java file:

Listing 2-9: The CClient.java File
start example
 /* Imports the java packages. */ import java.nio.*; import java.nio.channels.*; import java.nio.channels.spi.*; import java.util.*; import java.io.*; import java.net.*; /* Class CClient - Implements the methods declared or called in the chat application client. This _ file connects the chat client to chat server.    Method:       - addMessager()       - getBroadCastSender()       - getPrivateSender()       - connect()       - runClient()       - run()       - sendBroadMsg()       - sendListMsg()       - sendPrivateMessage() */ public class CClient extends Thread {    /* Declares the objects and initializes the variables. */    private String userId="";    private String pwd="";    ByteBuffer buffer=ByteBuffer.allocateDirect(1024);    SocketChannel Psc=null;    SocketChannel Asc=null;    private InetSocketAddress AAddr=null;    private InetSocketAddress PAddr=null;    private int APort=9999;    private int PPort=8888;    boolean connectStatus=false;    private ArrayList Lmsg=null;    private boolean Validity_Checker=false;    public Messager usrlist=null;    public Messager bcmsg=null;    public Messager prmsg=null;    boolean chkfirst=true;    /* Defines the default constructor. */    public CClient()    {    }    /* Implements the addMessager() method. */    public void addMessager(Messager usrlist, Messager bcmsg, Messager prmsg)    {       this.usrlist=usrlist;       this.bcmsg=bcmsg;       this.prmsg=prmsg;    }    /*Implements the connect() method. This method connects the specified user to the server.*/    public void connect(String UserId,String Password,String HostAddress) throws    NotYetConnectedException    {       this.userId=UserId;       this.pwd=Password;       try       {       Asc=SocketChannel.open(new InetSocketAddress(HostAddress,APort));       Psc=SocketChannel.open(new InetSocketAddress(HostAddress,PPort));       while(!Asc.finishConnect())       {       }       while(!Psc.finishConnect())       {       }       runClient();       sendBroadMsg("");       sendPrivateMessage(" "," ");       }       catch(Exception e1)       {          throw new NotYetConnectedException();       }    } /* Implements the runClient() method. This method runs the client. */    public void runClient() throws Exception    {       this.start();       new PrivateReceiver(Psc);    } /*Implements the run() method. This method is invoked when thread is started.*/ public void run()    {       byte[] Tdata=null;       while(true)       {          try          {             buffer.clear();             int nbyte=Asc.read(buffer);             if(nbyte==-1)             {                bcmsg.message("Connection Closed");                Asc.close();                return;             }             if (nbyte>0)             { /*Reads the messages from the chat server.*/ buffer.flip(); Tdata=new byte[nbyte]; buffer.get(Tdata,0,nbyte); if(Tdata[0]!=31)                {                   String s=new String(Tdata);                   bcmsg.message(s);                }                else                {                   String s=new String(Tdata);                   usrlist.message(s);                }             }          }          catch(IOException ex)          {             try             {                Asc.close();             }             catch(IOException ec)             {                ec.printStackTrace();             }          }       }    }  /*Implements the sendBroadMsg() method. This method broadcast the message to all the end users.*/    public void sendBroadMsg(String msg)    {       try       {          if(!connectStatus)          {             String tmps=userId+(char)28+pwd+(char)29+"";             ByteBuffer b=ByteBuffer.wrap(tmps.getBytes());             Asc.write(b);             connectStatus=true;          }          else          {             ByteBuffer b=ByteBuffer.wrap(msg.getBytes());             Asc.write(b);          }       }       catch(Exception sb)       {           sb.printStackTrace();       }    } /*Implements the sendListMsg() method. This method sends the user list to the end user.*/ public void sendListMsg(String msg)    {       try       {          String tmps=""+(char)31+"";          ByteBuffer b=ByteBuffer.wrap(tmps.getBytes());          Asc.write(b);       }       catch(Exception sl)       {           sl.printStackTrace();       }    } /*Implements the sendPrivateMessage() method.*/ public void sendPrivateMessage(String Msg,String to)    {       try       {          String Ts=null;          if(chkfirst)          {             Ts=to+(char)3+userId+(char)3+Msg;             chkfirst=false;          }          else             Ts=to+(char)3+Msg;             ByteBuffer b=ByteBuffer.wrap(Ts.getBytes());             Psc.write(b);       }       catch(Exception se)       {           se.printStackTrace();       }    }    /*Creates the PrivateReceiver class.*/    class PrivateReceiver extends Thread    {       SocketChannel P_channel=null;       ByteBuffer buff=ByteBuffer.allocateDirect(1024);       byte[] Tdata=null;       /*Defines the default constructor.*/       PrivateReceiver(SocketChannel chan )       {           this.P_channel=chan;          start();       }       /*Implements the run() method.*/       public void run()       {          while(true)          {             try             {                buff.clear();                int nbyte=P_channel.read(buff);                if(nbyte==-1)                {                   prmsg.message("Connection Closed");                   P_channel.close();                   return;                }                if (nbyte>0)                {                      /* Reads the data. */                   buff.flip();                   Tdata=new byte[nbyte];                   buff.get(Tdata,0,nbyte);                   String s=new String(Tdata);                   prmsg.message(s);                }             }             catch(IOException ex)             {                   try                {                P_channel.close();                }                catch(IOException ec)                {                   ec.printStackTrace();                }             }          }        }      };   } 
end example
 

Download this Listing .

In the above code, the CClient class defines the default contractor. The methods defined in this code are:

  • addMessager() : Retrieves the user list, broadcast message, and private message.

  • connect() : Opens two sockets to send private and broadcast messages. This method then calls the runClient(), sendBroadMsg(), and sendPrivateMsg() methods.

  • runClient() : Starts a thread, initializes the object of the PrivateReceiver class, and invokes the run() method.

  • run() : Reads the bytes from the socket to the buffer and separates the user name and broadcast message from the received message. The run() method then calls the message() method to send the broadcast message and the user list.

  • sendBroadMsg() : Checks the connection status, wraps the message to the byte buffer, and writes the buffer to the server socket.

  • sendListMsg() : Wraps the message to the byte buffer and writes the buffer to the server socket.

  • sendPrivateMessage() : Checks the destination user id, wraps the message to the byte buffer, and writes the buffer to the server socket.

The CClient class contains a sub class, PrivateReceiver, which receives the message from the server. This class defines the default constructor that calls the start() method of the Thread class to invoke the run() method. The run() method clears the buffer and reads the bytes from the channel to the buffer. This method then flips the buffer and calls the message() method to send a private message.

Creating Messager.java File

The Messager.java file creates an interface that declares the message() method. This method helps display the message in the text pane of the chat client window.

Listing 2-10 shows the contents of the Messager.java file:

Listing 2-10: The Messager.java File
start example
 /*Defines an abstract method to read and write the message to the text pane of the chat _ application client.*/ public interface Messager {    /*Declares the message() method.*/    public void message(String msg); } 
end example
 

Download this Listing .

In the above code, the Messager interface declares an abstract message() method. This method is defined later, where this interface is implemented to send or receive message from the chat server..




Java InstantCode. Developing Applications Using Java NIO
Java InstantCode. Developing Applications Using Java NIO
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 55

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net