ພັນລາວ.ຄອມ
ຊອກຫາ:
ຊອກຫາແບບລະອຽດ
ຂຽນເມື່ອ ຂຽນເມື່ອ: ກ.ພ.. 28, 2012 | ມີ 8 ຄຳເຫັນ ແລະ 0 trackback(s)

Client


import javax.swing.*;

 

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.io.*;

import java.util.StringTokenizer;

 

public class Client extends JFrame

{//here is a code for set frame

JPanel p1 = new JPanel();//p1 panel is a top area of display

JLabel lab1 = new JLabel("Username");//put user name to the box

JTextField tf1 = new JTextField(5);//put user name area

JLabel lab3 = new JLabel("Password");//put password to the box

JPasswordField tf3 = new JPasswordField(5);//put password area

JButton b1 = new JButton("login");//login note

JButton b2 = new JButton("Exit");//exit button

//JButton b5 = new JButton("Register"); //register button

 

//***************************************************************

JPanel p4 = new JPanel();//p4 panel is a center area of display

JScrollPane sp = new JScrollPane();//message will show in here when you have chat to somone

JTextArea ta = new JTextArea(12,28);//show message text area size

List list = new List(10);//this list use for show that who was login for use this client

 

JRadioButton rb1 = new JRadioButton("Mainroom",true);//choose for chat at main room

JRadioButton rb2 = new JRadioButton("Privatechat");//choose for chat with some one

ButtonGroup bg = new ButtonGroup();//this is a single choose about "Mainroom" and "Private"

JPanel p3 = new JPanel();//this is a new panel,we set it on the p4 panel for add "list","Mainrom" and "Private"

 

 

//**************************************************************************

JPanel p2 = new JPanel();

JTextField tf2 = new JTextField(20);

JButton b3 = new JButton("Sent");//sent message note

JButton b4 = new JButton("Emoticon");// show for choose Emotion Icon

JLabel lab2 = new JLabel("Message ");//Attention that" this is type your message

 

 

Socket socket;

PrintStream ps;

String name;

String Password;

String ip;

 

public Client()

{

       super("Chatroom");

       /* we depart the frame for 3 part as a panel1,panel2 and panel4 */

       getContentPane().add(p1,BorderLayout.NORTH);

       getContentPane().add(p4,BorderLayout.CENTER);

       getContentPane().add(p2,BorderLayout.SOUTH);

       pack();

 

   

       p1.add(lab1);//add "Username label" to panel 1

       p1.add(tf1);//add "Text for type usernae" to panel 1

       p1.add(lab3);//add "Password label" to panel 1

       p1.add(tf3);//add "Text for type passowrd" to panel 1

       p1.add(b1);//add "login" button to panel 1

      // p1.add(b5);//add"Register button" to p1

       p1.add(b2);//add "Exit" button to panel 1

       p2.add(b4);//add "Emoticon button" to panel 2

       p2.add(lab2);//add "Message label" to panel 2

       p2.add(tf2);//add" Text for type message " to panel 2

       p2.add(b3);//add"Sent button" to panel 2

      

 

       p3.setLayout(new BorderLayout());/*here we set a new panel as a panel 3,

       p3 is a part of p4 area*/

       /*we depart p3 as a 3 part for add "list","rb1,rb2"

        * (rb1 and rb2 is a single choose for chat "mainroom and Private")*/

      

       p3.add(list,BorderLayout.NORTH);//set top part of p3 for add "list"

       p3.add(rb1,BorderLayout.CENTER);//set midle part of p3 for add "Mainroom chat style"

       p3.add(rb2,BorderLayout.SOUTH);//set bottom part of p3 for add "Private chat style"

       /*"bg" in here is a short character for ButtonGroup command code

         use this command code for single choose*/

       bg.add(rb1);//add "Mainroom" to "ButtoGroup" for single choose

       bg.add(rb2);//add "Private chat" to "ButtoGroup" for single choose

      

       sp.getViewport().add(ta);

       p4.add(p3);//here is add panel 3 to panel 4 area

       p4.add(sp);/*here is add the display that will client chat to some another client

                    all of message will show in here display*/

      

      

       //Chat room display

       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

       Dimension frameSize = this.getSize();

       if(frameSize.width > screenSize.width)

       {

         frameSize.width = screenSize.width;

       }

       if(frameSize.height > screenSize.height)

       {

         frameSize.height = screenSize.height;

       }

       setLocation((screenSize.width - frameSize.width)/2,

                   (screenSize.height - frameSize.height)/2);

       setSize(600,380);//set frame size

       setVisible(true);

       setResizable(false);

       // set a register display

      /*b5.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e){

              System.out.println("reg clicked");

              new frameReg();

        }

     

      });*/

       b4.addActionListener(new ActionListener(){

         public void actionPerformed(ActionEvent e){

              System.out.println("pics clicked");

              new JWindow();

       }

       });

      

       b2.setEnabled(false);

      

 

       b1.addActionListener(new ActionListener()

       {

         public void actionPerformed(ActionEvent e)

         {

            try

            {

                   socket = new Socket(InetAddress.getLocalHost(),7000);

                   if(socket != null)

                   {

                     StringBuffer msg = new StringBuffer("CONNECT:");

                     name = tf1.getText();

                     Password = tf3.getText();

                  

                     ip = InetAddress.getLocalHost().toString();

                     msg.append(name+":"+ip+":"+Password);

                     ps = new PrintStream(socket.getOutputStream());

                     ps.println(msg);

                     ps.flush();

                     ta.setText("");

                 

                     ta.append(name+"login success"+" ");

                     b1.setEnabled(false);

                     b2.setEnabled(true);

                     //Cient accept message from server

                     Thread t = new ClientListener(socket);

                     t.start();

                   }

            }

            catch(IOException ex)

            {

                   ta.append("Error: "+ex+" ");

            }

         }

       });

       b2.addActionListener(new ButtonListener());//"Exit Button"

       b3.addActionListener(new ButtonListener());

       addWindowListener(new WindowAdapter()

       {

         public void windowClosing(WindowEvent e)

         {

            if(socket != null)

            {

                   ps.println("QUIT:" + name);

                   ps.flush();

                   closeSocket();

            }

            System.exit(0);

         }

       });

}

 

class ClientListener extends Thread

{

       Socket socket;

       BufferedReader br;

       PrintStream ps;

       String message;

 

       public ClientListener(Socket s)

       {

         try

         {

            socket = s;

            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            ps = new PrintStream(socket.getOutputStream());

         }

         catch(IOException ex)

         {

            ta.append("Error: "+ex+" ");

         }

       }

 

       public void run()

       {

         while(true)

         {

            try

            {

                   message = br.readLine();

                   if(message == null)

                     break;

            }

            catch(IOException ex)

            {

                   ta.append("Error-debug: "+ex+" ");

            }

            StringTokenizer st = new StringTokenizer(message,":");

            String keyword = st.nextToken();

 

            if(keyword.equals("PEOPLE"))

            {

                   list.removeAll();

                   while(st.hasMoreTokens())

                   {

                     String user = st.nextToken();

                     list.add(user);

                   }

            }

            else if(keyword.equals("MSG"))

            {

                   String broadcast = st.nextToken();

                   String user = st.nextToken();

                   StringBuffer sb = new StringBuffer(user+st.nextToken(""));

                   ta.append(sb+" ");

            }

            else if(keyword.equals("QUIT"))

            {

                   String who = st.nextToken();

                   if(who.equals("Server"))

                   {

                     closeSocket();

                     ta.append("Server had closed" + " ");

                     list.removeAll();

                     b2.setEnabled(false);

                   }

                   else

                   {

                     closeSocket();

                     b1.setEnabled(true);

                     b2.setEnabled(false);

                     list.removeAll();

                     ta.append(name + "Exit form chatroom" + " ");

                   }

                   break;

            }

         }

       }

}

 

public void closeSocket()

{

       if(socket != null)

       {

         try

         {

            socket.close();

         }

         catch (IOException ex)

         {

            ta.append("Error: " + ex + " ");

         }

       }

}

 

class ButtonListener implements ActionListener

{

       public void actionPerformed(ActionEvent e)

       {

         if(e.getActionCommand().equals("Exit"))

         {

            ps.println("QUIT:" + name);

            ps.flush();

         }

         else if(e.getActionCommand().equals("Sent"))

         {

            StringBuffer msg = new StringBuffer("MSG:");

            String info = name+":"+tf2.getText();

 

            if(rb1.isSelected())

            {

                   msg.append("BROAD:"+info);

            }

            else

            {

                   msg.append( list.getSelectedItem()+":"+info);

            }

            ps.println(msg);

            ps.flush();

            tf2.setText("");

         }

       }

}

 

public static void main(String[] args)

{

       Client app = new Client();

}

}

 

ຂຽນເມື່ອ ຂຽນເມື່ອ: ກ.ພ.. 28, 2012 | ມີ 6 ຄຳເຫັນ ແລະ 0 trackback(s)

 

SERVER

import java.awt.*;

import java.awt.event.*;

 

import javax.swing.*;

import javax.swing.event.MenuEvent;

import javax.swing.event.MenuListener;

 

import java.net.*;

import java.util.*;

import java.io.*;

 

public class Server extends JFrame

{

JMenuBar mb = new JMenuBar();

JMenu m1 = new JMenu("File");

JMenuItem mi1 = new JMenuItem("Connect");

 

JMenuItem mi2 = new JMenuItem("Exit");

 

JMenu m2 = new JMenu("Help");

JOptionPane mi3 = new JOptionPane("If you want to use this server chatroom please click at 'File' and choose Connect first for client connect. If you want to stop server chatroom please shoose 'Exit.'");

JLabel lab1 = new JLabel("Online User");

JLabel lab2 = new JLabel("Message");

 

JTextArea ta = new JTextArea(9,30);

java.awt.List list = new java.awt.List(9);

JTextField tf = new JTextField(22);

JButton b = new JButton("Sent");

JButton e = new JButton("Emoticon");

JScrollPane sp = new JScrollPane();

 

JPanel p1 = new JPanel();

JPanel p2 = new JPanel();

JPanel p3 = new JPanel();

 

ServerSocket serverSocket;

Socket socket;

ArrayList array = new ArrayList();

int connect;

 

public Server()

{

       super("Server Chatroom");

       setJMenuBar(mb);

       mb.add(m1);

       mb.add(m2);

       m1.add(mi1);

       m1.addSeparator();

       m1.add(mi2);

       m2.add(mi3);

       sp.getViewport().add(ta);

       p1.setLayout(new BorderLayout());

       p3.add(lab1);

       p1.add(p3,BorderLayout.NORTH);

       p1.add(list,BorderLayout.SOUTH);

       p2.add(e);

    

       p2.add(lab2);

       p2.add(tf);

       p2.add(b);

       getContentPane().add(sp,BorderLayout.NORTH);

       getContentPane().add(p1,BorderLayout.CENTER);

       getContentPane().add(p2,BorderLayout.SOUTH);

       pack();


       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

       Dimension frameSize = this.getSize();

       if(frameSize.width > screenSize.width)

       {

         frameSize.width = screenSize.width;

       }

       if(frameSize.height > screenSize.height)

       {

         frameSize.height = screenSize.height;

       }

       setLocation((screenSize.width - frameSize.width)/2,

                   (screenSize.height - frameSize.height)/2);

       setSize(500,430);

       setVisible(true);

       setResizable(false);

      

 

       mi1.addActionListener(new ActionListener()

       {

         public void actionPerformed(ActionEvent e)

         {

            if(serverSocket == null)

            {

                   try

                   {

                     serverSocket = new ServerSocket(7000);

                     ta.append("System imformation"+"                Server Chatroom"

                              +"                Now Starting...... ");

                   }

                   catch(IOException ex)

                   {

                     ta.append("System imformation"+"                Server Chatroom"

                              +"                Starting fail ");

                   }

            }

            else

            {

                   ta.append("System imformation"+"                Server Chatroom"

                           +"                Starting copleted...... ");

            }

         

            Thread t = new Watch();

            t.start();

         }

       });

       mi2.addActionListener(new ServerListener());

       b.addActionListener(new ServerListener());

       addWindowListener(new WindowAdapter()

       {

         public void windowClosing(WindowEvent e)

         {

            closeAll();

            System.exit(0);

         }

       });

}

 

class Watch extends Thread

{

       public void run()

       {

         while(true)

         {

            if(array.size() <= 10)

            {

                   try

                   {

                     socket = serverSocket.accept();

                   }

                   catch(IOException ex)

                   {

                     ta.append("System imformation                "+ex+" ");

                   }

             

               Client c = new Client(socket);

               array.add(c);

               c.start();

            }

            else

            {

          ta.append("System imformation"+"                Server Chatroom"

                   +"               

            }

         }

       }

}

 

class Client extends Thread

{

       String name;

       String ip;

       String ipAddress;

       Socket socket;

       BufferedReader br;

       PrintStream ps;

 

       public Client(Socket s)

       {

         try

         {

            socket = s;

            br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            ps = new PrintStream(s.getOutputStream());

         }

         catch (IOException ex)

         {

            ta.append("System imformation                "+ex+" ");

         }

       }

 

       public void run()

       {

         String info;

         try

         {

            while(true)

            {

                   info = br.readLine();

                   if(info == null)

                     break;

                   StringTokenizer st = new StringTokenizer(info, ":");

                   String keyword = st.nextToken();

 

          

                   if (keyword.equals("CONNECT"))

                   {

                     name = st.nextToken();

                     ip = st.nextToken();

                     ipAddress = ip.substring(ip.indexOf("/")+1);

                     ta.append("System imformation                " + name + "/"

                              + ipAddress +"                Connected ");

                     list.add(name + "                    " + ip

                              +"                    User login completed");

                     notifyChatRoom();

                   }

                   else if (keyword.equals("MSG"))

                   {

                     String broadcast = st.nextToken();

                     StringBuffer message = new StringBuffer("MSG:" +broadcast);

                     message.append(st.nextToken(""));

                     if (broadcast.equals("BROAD"))

                     {

                        sendToClients(message);

                     }

                     else

                     {

                        sendToClient(message, broadcast);

                     }

                   }

                   else if (keyword.equals("QUIT"))

                   {

                     disConnect(this);

                     list.removeAll();

                     for (int i = 0; i < array.size(); i++)

                     {

                        Client c = (Client) array.get(i);

                        list.add(c.name + "                    " + c.ip

                                 +"                    User login completed", i);

                     }

                     notifyChatRoom();

                     break;

                   }

            }

         }

         catch (IOException ex)

         {

            ta.append("System imformation                "+ex+" ");

            disConnect(this);

            notifyChatRoom();

         }

       }

 

       public void send(StringBuffer msg)

       {

         ps.println(msg);

         ps.flush();

       }

}

 

public synchronized void sendToClients(StringBuffer msg)

{

       for(int i=0;i<array.size();i++)

       {

         Client c = (Client)array.get(i);

         c.send(msg);

       }

}

 

public synchronized void sendToClient(StringBuffer msg,String s)

{

       for(int i=0;i<array.size();i++)

       {

         Client c = (Client)array.get(i);

         if(c.name.equals(s))

         {

            c.send(msg);

            break;

         }

       }

}

 


public void notifyChatRoom()

{

       StringBuffer sb = new StringBuffer("PEOPLE");

       for(int i=0;i<array.size();i++)

       {

         Client c =(Client)array.get(i);

         sb.append(":"+c.name);

       }

       sendToClients(sb);

}

 

public synchronized void disConnect(Client c)

{

   try

   {

          ta.append("System imformation                " + c.name+ "/"

                  + c.ipAddress +"                User was left ");

          c.send(new StringBuffer("QUIT:"+c.name));

          c.socket.close();

          array.remove(c);

   }

   catch(IOException ex)

   {

          ta.append("System imformation                "+ex+" ");

   }

}

 

public void closeAll()

{

   sendToClients(new StringBuffer("QUIT:"+"Server"));

   while(array.size()>0)

   {

      try

          {

            for(int i=0;i<array.size();i++)

            {

               Client c = (Client)array.get(i);

               c.socket.close();

               array.remove(c);

            }

          }

          catch(IOException ex)

          {

            ta.append("System imformation                "+ex+" ");

          }

   }

}

 

class ServerListener implements ActionListener

{

   public void actionPerformed(ActionEvent e)

   {

          if(e.getActionCommand().equals("Sent"))

          {

            StringBuffer msg = new StringBuffer("MSG:"+"BROAD:");

            msg.append("Server:"+tf.getText());

            sendToClients(msg);

            tf.setText("");

          }

          else if(e.getActionCommand().equals("Exit"))

          {

            closeAll();

            System.exit(0);

          }

   }

}

 

public static void main(String[] args)

{

       Server app = new Server();

}

}