aquaballoon

Java - Chatting Room

Jun 30th, 2014
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 37.16 KB | None | 0 0
  1. // Server.java
  2. package chatRoom;
  3.  
  4. import java.io.IOException;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. import java.util.ArrayList;
  8.  
  9. public class Server {
  10.  
  11.     private ServerSocket serverSocket;
  12.     ArrayList<NewClient> clientArray = new ArrayList<NewClient>();
  13.  
  14.     int PORT = 4447;
  15.     //int MAX = 30;
  16.  
  17.     public Server() throws IOException {
  18.  
  19.         serverSocket = new ServerSocket(PORT);
  20.         System.out.println("Server Connected...");
  21.  
  22.         while (true) {
  23.             Socket clientSocket = serverSocket.accept(); //accept new client
  24.             NewClient newClient = new NewClient(this, clientSocket);
  25.             newClient.start();
  26.  
  27.             // clientArray will be added after receiving message from client
  28.             clientArray.add(newClient); // add client socket to ArrayList
  29.         }
  30.     }
  31.  
  32.     public void sendToAll(String msgFromClient) {
  33.        
  34.     }
  35.  
  36.     public static void main(String[] args) throws IOException {
  37.         new Server();
  38.     }
  39. }
  40.  
  41. // NewClient.java
  42. package chatRoom;
  43.  
  44. import java.io.BufferedReader;
  45. import java.io.IOException;
  46. import java.io.InputStreamReader;
  47. import java.io.PrintWriter;
  48. import java.net.Socket;
  49. import java.util.StringTokenizer;
  50.  
  51. public class NewClient extends Thread {
  52.  
  53.     Socket clientSocket;
  54.     Server server;
  55.  
  56.     BufferedReader in;
  57.     PrintWriter out;
  58.  
  59.     String loginName = "";
  60.     String loginIP = "";
  61.  
  62.     // LOGIN
  63.     public NewClient(Server server, Socket clientSocket) throws IOException {
  64.  
  65.         this.server = server;
  66.         this.clientSocket = clientSocket;
  67.  
  68.         in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  69.         out = new PrintWriter(clientSocket.getOutputStream());
  70.  
  71.         String loginInfo = in.readLine();
  72.         // userName@/127.0.0.1 => (userName, userIP)
  73.         StringTokenizer tok = new StringTokenizer(loginInfo, "@");
  74.  
  75.         loginName = tok.nextToken();
  76.         loginIP = tok.nextToken();
  77.  
  78.         sendToMe("Welcome " + loginName + loginIP);
  79.  
  80.         // ==> send the list of chatters to clients <==
  81.         // clientArray is not added in the beginning
  82.         // is added after run()
  83.         // new user
  84.         //server.clientArray.add(this);
  85.         if (server.clientArray.size() > 0) {
  86.             String temp = "";
  87.             for (NewClient newClient : server.clientArray) {
  88.                 temp += (newClient.loginName + newClient.loginIP) + "@";
  89.             }
  90.             // send other's login info to me
  91.             sendToMe("USERLIST@" + server.clientArray.size() + "@" + temp);
  92.         }
  93.  
  94.         // old user
  95.         for (NewClient newClient : server.clientArray) {
  96.             // send my login info to other
  97.             newClient.sendToMe("ADD@" + loginName + loginIP);
  98.         }
  99.     }
  100.  
  101.     // RECEIVING MESSAGE
  102.     public void run() {
  103.         String msgFromClient = null;
  104.         while (true) {
  105.             try {
  106.                 // msgFromClient = username@ALL@hello world
  107.                 msgFromClient = in.readLine();
  108.  
  109.                 if (msgFromClient.equals("CLOSE")) {
  110.  
  111.                     in.close();
  112.                     out.close();
  113.                     clientSocket.close();
  114.  
  115.                     for (NewClient newClient : server.clientArray) {
  116.                         newClient.sendToMe("DELETE@" + loginName);
  117.                     }
  118.  
  119.                     server.clientArray.remove(this);
  120.  
  121.                     return;  // error without "return"
  122.  
  123.                 } else {
  124.  
  125.                     // msgFromClient = username@ALL@hello world
  126.                     StringTokenizer tok = new StringTokenizer(msgFromClient, "@");
  127.  
  128.                     String sender = tok.nextToken();
  129.                     String receiver = tok.nextToken();
  130.                     String content = tok.nextToken();
  131.  
  132.                     for (NewClient newClient : server.clientArray) {
  133.                         if (receiver.equals("ALL")) {
  134.                             if (!sender.equals(newClient.getUserName())) {
  135.                                 msgFromClient = sender + ": " + content;
  136.                                 newClient.sendToMe(msgFromClient);
  137.                             } else {
  138.                                 msgFromClient = "Me" + ": " + content;
  139.                                 sendToMe(msgFromClient);
  140.                             }
  141.                         } else if (!receiver.equals("ALL")) {
  142.                             if (newClient.getUserName().equals(receiver)) {
  143.                                 msgFromClient = sender + ": " + content;
  144.                                 newClient.sendToMe(msgFromClient);
  145.                             }
  146.                         }
  147.                     }
  148.                 }
  149.             } catch (IOException e) {
  150.                 e.printStackTrace();
  151.             }
  152.         }
  153.     }
  154.  
  155.     public void sendToMe(String msg) {
  156.         out.println(msg);
  157.         out.flush();
  158.     }
  159.  
  160.     public String getUserName() {
  161.         return loginName;
  162.     }
  163.  
  164.     public String getUserIP() {
  165.         return loginIP;
  166.     }
  167. }
  168.  
  169. // ChatGUI.java
  170. package chatRoom;
  171.  
  172. import java.awt.event.KeyEvent;
  173. import java.io.BufferedReader;
  174. import java.io.IOException;
  175. import java.io.InputStreamReader;
  176. import java.io.PrintWriter;
  177. import java.net.Socket;
  178. import java.util.StringTokenizer;
  179. import javax.swing.DefaultListModel;
  180. import javax.swing.JOptionPane;
  181.  
  182. /**
  183.  *
  184.  * @author jlee
  185.  */
  186. public class ChatGUI extends javax.swing.JFrame {
  187.  
  188.     String hostIP = "127.0.0.1";  // server ip "localhost"
  189.     int port = 4447;
  190.  
  191.     private Socket socket;
  192.     private PrintWriter out;
  193.     private BufferedReader in;
  194.  
  195.     private ReceiveMessage receiveMessage;
  196.     private boolean isConnected = false;
  197.  
  198.     private DefaultListModel listModel;
  199.  
  200.     public ChatGUI() throws IOException {
  201.         listModel = new DefaultListModel();
  202.         initComponents();
  203.     }
  204.  
  205.     @SuppressWarnings("unchecked")
  206.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  207.     private void initComponents() {
  208.  
  209.         buttonGroup = new javax.swing.ButtonGroup();
  210.         inLogin = new javax.swing.JTextField();
  211.         jScrollPane1 = new javax.swing.JScrollPane();
  212.         outMessage = new javax.swing.JTextArea();
  213.         btStart = new javax.swing.JButton();
  214.         jScrollPane2 = new javax.swing.JScrollPane();
  215.         userList = new javax.swing.JList(listModel);
  216.         jPanel1 = new javax.swing.JPanel();
  217.         btExit = new javax.swing.JButton();
  218.         radioWisper = new javax.swing.JRadioButton();
  219.         radioPublic = new javax.swing.JRadioButton();
  220.         inMessage = new javax.swing.JTextField();
  221.         btSend = new javax.swing.JButton();
  222.  
  223.         setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
  224.  
  225.         outMessage.setEditable(false);
  226.         outMessage.setColumns(20);
  227.         outMessage.setRows(5);
  228.         jScrollPane1.setViewportView(outMessage);
  229.  
  230.         btStart.setText("Start");
  231.         btStart.addActionListener(new java.awt.event.ActionListener() {
  232.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  233.                 btStartActionPerformed(evt);
  234.             }
  235.         });
  236.  
  237.         userList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
  238.             public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
  239.                 userListValueChanged(evt);
  240.             }
  241.         });
  242.         jScrollPane2.setViewportView(userList);
  243.  
  244.         javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
  245.         jPanel1.setLayout(jPanel1Layout);
  246.         jPanel1Layout.setHorizontalGroup(
  247.             jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  248.             .addGap(0, 0, Short.MAX_VALUE)
  249.         );
  250.         jPanel1Layout.setVerticalGroup(
  251.             jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  252.             .addGap(0, 53, Short.MAX_VALUE)
  253.         );
  254.  
  255.         btExit.setText("Exit");
  256.         btExit.addActionListener(new java.awt.event.ActionListener() {
  257.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  258.                 btExitActionPerformed(evt);
  259.             }
  260.         });
  261.  
  262.         buttonGroup.add(radioWisper);
  263.         radioWisper.setText("Wisper");
  264.  
  265.         buttonGroup.add(radioPublic);
  266.         radioPublic.setSelected(true);
  267.         radioPublic.setText("Public");
  268.  
  269.         inMessage.addActionListener(new java.awt.event.ActionListener() {
  270.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  271.                 inMessageActionPerformed(evt);
  272.             }
  273.         });
  274.         inMessage.addKeyListener(new java.awt.event.KeyAdapter() {
  275.             public void keyReleased(java.awt.event.KeyEvent evt) {
  276.                 inMessageKeyReleased(evt);
  277.             }
  278.         });
  279.  
  280.         btSend.setText("Send");
  281.         btSend.addActionListener(new java.awt.event.ActionListener() {
  282.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  283.                 btSendActionPerformed(evt);
  284.             }
  285.         });
  286.  
  287.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  288.         getContentPane().setLayout(layout);
  289.         layout.setHorizontalGroup(
  290.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  291.             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  292.                 .addContainerGap()
  293.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  294.                     .addGroup(layout.createSequentialGroup()
  295.                         .addComponent(inLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
  296.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  297.                         .addComponent(btStart)
  298.                         .addGap(4, 4, 4)
  299.                         .addComponent(btExit, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
  300.                     .addGroup(layout.createSequentialGroup()
  301.                         .addComponent(inMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
  302.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  303.                         .addComponent(btSend))
  304.                     .addGroup(layout.createSequentialGroup()
  305.                         .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
  306.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  307.                             .addGroup(layout.createSequentialGroup()
  308.                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  309.                                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  310.                                     .addComponent(radioWisper)
  311.                                     .addComponent(radioPublic))
  312.                                 .addGap(0, 0, Short.MAX_VALUE))
  313.                             .addGroup(layout.createSequentialGroup()
  314.                                 .addGap(4, 4, 4)
  315.                                 .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))))
  316.                 .addGap(11, 11, 11)
  317.                 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  318.                 .addGap(0, 0, 0))
  319.         );
  320.         layout.setVerticalGroup(
  321.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  322.             .addGroup(layout.createSequentialGroup()
  323.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  324.                     .addGroup(layout.createSequentialGroup()
  325.                         .addGap(10, 10, 10)
  326.                         .addComponent(inLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  327.                     .addGroup(layout.createSequentialGroup()
  328.                         .addContainerGap()
  329.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  330.                             .addComponent(btExit)
  331.                             .addComponent(btStart))))
  332.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  333.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  334.                     .addGroup(layout.createSequentialGroup()
  335.                         .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
  336.                         .addGap(14, 14, 14)
  337.                         .addComponent(radioPublic)
  338.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  339.                         .addComponent(radioWisper))
  340.                     .addComponent(jScrollPane1))
  341.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  342.                     .addGroup(layout.createSequentialGroup()
  343.                         .addGap(0, 0, Short.MAX_VALUE)
  344.                         .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  345.                     .addGroup(layout.createSequentialGroup()
  346.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  347.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  348.                             .addComponent(inMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  349.                             .addComponent(btSend))
  350.                         .addContainerGap())))
  351.         );
  352.  
  353.         pack();
  354.     }// </editor-fold>                        
  355.  
  356.     private void inMessageActionPerformed(java.awt.event.ActionEvent evt) {                                          
  357.         send();
  358.     }                                        
  359.  
  360.     private void btSendActionPerformed(java.awt.event.ActionEvent evt) {                                      
  361.         send();
  362.     }                                      
  363.  
  364.     private void btExitActionPerformed(java.awt.event.ActionEvent evt) {                                      
  365.         // TODO add your handling code here:
  366.         if (!isConnected) {
  367.             JOptionPane.showMessageDialog(this, "Is not connected!",
  368.                     "", JOptionPane.ERROR_MESSAGE);
  369.             return;
  370.         }
  371.         try {
  372.  
  373.             // close connection to server
  374.             boolean flag = closeConnection();
  375.  
  376.             if (flag == false) {
  377.                 throw new Exception("Close error");
  378.             }
  379.  
  380.             JOptionPane.showMessageDialog(this, "Bye.");
  381.  
  382.         } catch (Exception exc) {
  383.             JOptionPane.showMessageDialog(this, exc.getMessage(),
  384.                     "", JOptionPane.ERROR_MESSAGE);
  385.         }
  386.  
  387.     }                                      
  388.  
  389.     private void inMessageKeyReleased(java.awt.event.KeyEvent evt) {                                      
  390.         // TODO add your handling code here:
  391. //        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
  392. //            send();
  393. //        }
  394.     }                                    
  395.  
  396.     private void btStartActionPerformed(java.awt.event.ActionEvent evt) {                                        
  397.         // TODO add your handling code here:
  398.  
  399.         if (isConnected) {
  400.             JOptionPane.showMessageDialog(this, "isConnected",
  401.                     "", JOptionPane.ERROR_MESSAGE);
  402.             return;
  403.         }
  404.         try {
  405.             String name = inLogin.getText().trim();
  406.  
  407.             // ====> connect to server
  408.             boolean flag = connectServer(port, hostIP, name);
  409.  
  410.             if (flag == false) {
  411.                 throw new Exception("Connection error");
  412.             }
  413.  
  414.             this.setTitle(name);
  415.             JOptionPane.showMessageDialog(this, "Welcome " + name);
  416.  
  417.         } catch (Exception exc) {
  418.             JOptionPane.showMessageDialog(this, exc.getMessage(),
  419.                     "", JOptionPane.ERROR_MESSAGE);
  420.         }
  421.  
  422.  
  423.     }                                      
  424.  
  425.     private void userListValueChanged(javax.swing.event.ListSelectionEvent evt) {                                      
  426.         // TODO add your handling code here:
  427.     }                                    
  428.  
  429.     //LOGIN
  430.     public boolean connectServer(int port, String hostIP, String name) {
  431.  
  432.         try {
  433.             socket = new Socket(hostIP, port);
  434.  
  435.             out = new PrintWriter(socket.getOutputStream());
  436.             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  437.  
  438.             //LOGIN
  439.             // name@/x.x.x.x
  440.             sendMessage(name + "@" + socket.getLocalAddress().toString());
  441.  
  442.             //receive message
  443.             //receiveMessage = new ReceiveMessage(in, textArea);
  444.             receiveMessage = new ReceiveMessage();
  445.             receiveMessage.start();
  446.  
  447.             isConnected = true;
  448.             return true;
  449.  
  450.         } catch (Exception e) {
  451.             outMessage.append("Server port: " + port + "Server IP: " + hostIP + "\r\n");
  452.             isConnected = false;
  453.             return false;
  454.         }
  455.     }
  456.  
  457.     @SuppressWarnings("deprecation")
  458.     public synchronized boolean closeConnection() {
  459.         try {
  460.  
  461.             sendMessage("CLOSE");
  462.             receiveMessage.stop(); //NullPointerException
  463.  
  464.             if (in != null) {
  465.                 in.close();
  466.             }
  467.             if (out != null) {
  468.                 out.close();
  469.             }
  470.             if (socket != null) {
  471.                 socket.close();
  472.             }
  473.  
  474.             isConnected = false;
  475.            
  476.             System.exit(0);
  477.            
  478.             return true;
  479.  
  480.         } catch (IOException e1) {
  481.             e1.printStackTrace();
  482.             isConnected = true;
  483.             return false;
  484.         }
  485.     }
  486.  
  487.     public void send() {
  488.         if (!isConnected) {
  489.             JOptionPane.showMessageDialog(this, "Is not connected!", "",
  490.                     JOptionPane.ERROR_MESSAGE);
  491.             return;
  492.         }
  493.  
  494.         String message = inMessage.getText().trim();
  495.  
  496.         if (message == null || message.equals("")) {
  497.             JOptionPane.showMessageDialog(this, "No message", "",
  498.                     JOptionPane.ERROR_MESSAGE);
  499.             return;
  500.         }
  501.        
  502.         // username@ALL@hello world
  503. //        sendMessage(this.getTitle() + "@" + "ALL" + "@" + message);
  504.  
  505.         if (radioWisper.isSelected()) {
  506.             String receiver = (String) userList.getSelectedValue();
  507.  
  508.             sendMessage(this.getTitle() + "@" + receiver + "@" + message);
  509.  
  510.         } else {
  511.             sendMessage(this.getTitle() + "@" + "ALL" + "@" + message);
  512.         }
  513.        
  514.         inMessage.setText(null);
  515.     }
  516.  
  517.     public void sendMessage(String message) {
  518.  
  519.         out.println(message);
  520.         out.flush();
  521.     }
  522.  
  523.     class ReceiveMessage extends Thread {
  524.  
  525.         public void run() {
  526.             String msgFromServer = "";
  527.             while (true) {
  528.                 try {
  529.  
  530.                     // => CLOSE, ADD@, DELETE@, USERLIST@, MAX@, or username: hi
  531.                     msgFromServer = in.readLine();
  532.                     System.out.println(msgFromServer);
  533.  
  534.                     // '/' or, '@'
  535.                     StringTokenizer tok = new StringTokenizer(msgFromServer, "/@");
  536.  
  537.                     String command = tok.nextToken();
  538.  
  539.                     // CLOSE
  540.                     if (command.equals("CLOSE")) {
  541.                         outMessage.append("Server closed!\r\n");
  542.                         removeUsers();
  543.                         return;
  544.                     } // MAX@username/x.x.x.x  
  545.                     //                    else if (command.equals("MAX")) {
  546.                     //                        textArea.append("Max limited!\r\n");
  547.                     //                        removeUsers();
  548.                     //                        return;
  549.                     //                    }
  550.                     // DELETE@username
  551.                     else if (command.equals("DELETE")) {
  552.  
  553.                         String username = tok.nextToken();
  554.  
  555.                         listModel.removeElement(username);
  556.  
  557.                         // ADD@username/x.x.x.x  
  558.                     } else if (command.equals("ADD")) {
  559.  
  560.                         String username = "";
  561.                         String userIp = "";
  562.  
  563.                         if ((username = tok.nextToken()) != null
  564.                                 && (userIp = tok.nextToken()) != null) {
  565.  
  566.                             listModel.addElement(username);
  567.                         }
  568.  
  569.                         // USERLIST@numOfUser@username@/x.x.x.x@username@/x.x.x.x        
  570.                     } else if (command.equals("USERLIST")) {
  571.  
  572.                         int numOfUser = Integer.parseInt(tok.nextToken());
  573.                         String username = null;
  574.                         String userIp = null;
  575.  
  576.                         for (int i = 0; i < numOfUser; i++) {
  577.                             username = tok.nextToken();
  578.                             userIp = tok.nextToken();
  579.  
  580.                             listModel.addElement(username);
  581.                         }
  582.  
  583.                         // username: hello world
  584.                     } else {
  585.                         outMessage.append(msgFromServer + "\r\n");
  586.                     }
  587.                 } catch (IOException e) {
  588.                     e.printStackTrace();
  589.                 } catch (Exception e) {
  590.                     e.printStackTrace();
  591.                 }
  592.             }
  593.         }
  594.  
  595.         public synchronized void removeUsers() throws Exception {
  596.  
  597.             listModel.removeAllElements();
  598.  
  599.             if (in != null) {
  600.                 in.close();
  601.             }
  602.             if (out != null) {
  603.                 out.close();
  604.             }
  605.             if (socket != null) {
  606.                 socket.close();
  607.             }
  608.             isConnected = false;
  609.         }
  610.     }  // end of ReceiveMessage class
  611.  
  612.     public static void main(String args[]) {
  613.         /* Set the Nimbus look and feel */
  614.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  615.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  616.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  617.          */
  618.         try {
  619.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  620.                 if ("Nimbus".equals(info.getName())) {
  621.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  622.                     break;
  623.                 }
  624.             }
  625.         } catch (ClassNotFoundException ex) {
  626.             java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  627.         } catch (InstantiationException ex) {
  628.             java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  629.         } catch (IllegalAccessException ex) {
  630.             java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  631.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  632.             java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  633.         }
  634.         //</editor-fold>
  635.  
  636.         /* Create and display the form */
  637.         java.awt.EventQueue.invokeLater(new Runnable() {
  638.             public void run() {
  639.                 try {
  640.                     new ChatGUI().setVisible(true);
  641.                 } catch (IOException ex) {
  642.                 }
  643.             }
  644.         });
  645.     }
  646.  
  647.     // Variables declaration - do not modify                    
  648.     private javax.swing.JButton btExit;
  649.     private javax.swing.JButton btSend;
  650.     private javax.swing.JButton btStart;
  651.     private javax.swing.ButtonGroup buttonGroup;
  652.     private javax.swing.JTextField inLogin;
  653.     private javax.swing.JTextField inMessage;
  654.     private javax.swing.JPanel jPanel1;
  655.     private javax.swing.JScrollPane jScrollPane1;
  656.     private javax.swing.JScrollPane jScrollPane2;
  657.     private javax.swing.JTextArea outMessage;
  658.     private javax.swing.JRadioButton radioPublic;
  659.     private javax.swing.JRadioButton radioWisper;
  660.     private javax.swing.JList userList;
  661.     // End of variables declaration                  
  662. }
  663.  
  664. // Client.java
  665. package chatRoom;
  666.  
  667. import java.awt.BorderLayout;
  668. import java.awt.Color;
  669. import java.awt.GridLayout;
  670. import java.awt.Toolkit;
  671. import java.awt.event.ActionEvent;
  672. import java.awt.event.ActionListener;
  673. import java.awt.event.WindowAdapter;
  674. import java.awt.event.WindowEvent;
  675. import java.io.BufferedReader;
  676. import java.io.IOException;
  677. import java.io.InputStreamReader;
  678. import java.io.PrintWriter;
  679. import java.net.Socket;
  680. import java.util.StringTokenizer;
  681.  
  682. import javax.swing.DefaultListModel;
  683. import javax.swing.JButton;
  684. import javax.swing.JFrame;
  685. import javax.swing.JLabel;
  686. import javax.swing.JList;
  687. import javax.swing.JOptionPane;
  688. import javax.swing.JPanel;
  689. import javax.swing.JScrollPane;
  690. import javax.swing.JSplitPane;
  691. import javax.swing.JTextArea;
  692. import javax.swing.JTextField;
  693. import javax.swing.border.TitledBorder;
  694.  
  695. public class Client {
  696.  
  697.     private JFrame frame;
  698.     private JList userList;
  699.     private JTextArea textArea;
  700.     private JTextField textField;
  701.     private JTextField txt_port;
  702.     private JTextField txt_hostIp;
  703.     private JTextField txt_name;
  704.     private JButton btn_start;
  705.     private JButton btn_stop;
  706.     private JButton btn_send;
  707.     private JPanel northPanel;
  708.     private JPanel southPanel;
  709.     private JScrollPane rightScroll;
  710.     private JScrollPane leftScroll;
  711.     private JSplitPane centerSplit;
  712.  
  713.     private Socket socket;
  714.     private PrintWriter out;
  715.     private BufferedReader in;
  716.    
  717.     private ReceiveMessage receiveMessage;
  718.     private boolean isConnected = false;
  719.    
  720.     private DefaultListModel listModel;
  721.  
  722.     public Client() {
  723.  
  724.         init();
  725.  
  726.         btn_start.addActionListener(new ActionListener() {
  727.             public void actionPerformed(ActionEvent e) {
  728.                 int port;
  729.                 if (isConnected) {
  730.                     JOptionPane.showMessageDialog(frame, "isConnected",
  731.                             "", JOptionPane.ERROR_MESSAGE);
  732.                     return;
  733.                 }
  734.                 try {
  735.                     try {
  736.                         port = Integer.parseInt(txt_port.getText().trim());
  737.                     } catch (NumberFormatException e2) {
  738.                         throw new Exception("Port error");
  739.                     }
  740.  
  741.                     String hostIp = txt_hostIp.getText().trim();
  742.  
  743.                     String name = txt_name.getText().trim();
  744.  
  745.                     if (name.equals("") || hostIp.equals("")) {
  746.                         throw new Exception("No Login");
  747.                     }
  748.  
  749.                     // ====> connect to server
  750.                     boolean flag = connectServer(port, hostIp, name);
  751.  
  752.                     if (flag == false) {
  753.                         throw new Exception("Connection error");
  754.                     }
  755.  
  756.                     frame.setTitle(name);
  757.                     JOptionPane.showMessageDialog(frame, "Welcome " + name);
  758.  
  759.                 } catch (Exception exc) {
  760.                     JOptionPane.showMessageDialog(frame, exc.getMessage(),
  761.                             "", JOptionPane.ERROR_MESSAGE);
  762.                 }
  763.             }
  764.         });
  765.  
  766.         btn_stop.addActionListener(new ActionListener() {
  767.             public void actionPerformed(ActionEvent e) {
  768.                 if (!isConnected) {
  769.                     JOptionPane.showMessageDialog(frame, "Is not connected!",
  770.                             "", JOptionPane.ERROR_MESSAGE);
  771.                     return;
  772.                 }
  773.                 try {
  774.  
  775.                     // close connection to server
  776.                     boolean flag = closeConnection();
  777.  
  778.                     if (flag == false) {
  779.                         throw new Exception("Close error");
  780.                     }
  781.                    
  782.                     JOptionPane.showMessageDialog(frame, "I am leaving.");
  783.                    
  784.                 } catch (Exception exc) {
  785.                     JOptionPane.showMessageDialog(frame, exc.getMessage(),
  786.                             "", JOptionPane.ERROR_MESSAGE);
  787.                 }
  788.             }
  789.         });
  790.  
  791.         frame.addWindowListener(new WindowAdapter() {
  792.             public void windowClosing(WindowEvent e) {
  793.                 if (isConnected) {
  794.                    
  795.                     // close connection to server
  796.                     closeConnection();
  797.                 }
  798.                 System.exit(0);
  799.             }
  800.         });
  801.  
  802.         textField.addActionListener(new ActionListener() {
  803.             public void actionPerformed(ActionEvent arg0) {
  804.                 send();
  805.             }
  806.         });
  807.  
  808.         btn_send.addActionListener(new ActionListener() {
  809.             public void actionPerformed(ActionEvent e) {
  810.                 send();
  811.             }
  812.         });
  813.  
  814.     }  // end of Client
  815.  
  816.     public void init() {
  817.  
  818.         textArea = new JTextArea();
  819.         textArea.setEditable(false);
  820.         textArea.setForeground(Color.blue);
  821.         textField = new JTextField();
  822.         txt_port = new JTextField("6666");
  823.         txt_hostIp = new JTextField("127.0.0.1");
  824.         txt_name = new JTextField("");
  825.         btn_start = new JButton("Start");
  826.         btn_stop = new JButton("Stop");
  827.         btn_send = new JButton("Send");
  828.         listModel = new DefaultListModel();
  829.         userList = new JList(listModel);
  830.  
  831.         northPanel = new JPanel();
  832.         northPanel.setLayout(new GridLayout(1, 7));
  833.         northPanel.add(new JLabel("Port"));
  834.         northPanel.add(txt_port);
  835.         northPanel.add(new JLabel("IP"));
  836.         northPanel.add(txt_hostIp);
  837.         northPanel.add(new JLabel("Login"));
  838.         northPanel.add(txt_name);
  839.         northPanel.add(btn_start);
  840.         northPanel.add(btn_stop);
  841.         northPanel.setBorder(new TitledBorder(""));
  842.  
  843.         rightScroll = new JScrollPane(textArea);
  844.         rightScroll.setBorder(new TitledBorder(""));
  845.         leftScroll = new JScrollPane(userList);
  846.         leftScroll.setBorder(new TitledBorder(""));
  847.         southPanel = new JPanel(new BorderLayout());
  848.         southPanel.add(textField, "Center");
  849.         southPanel.add(btn_send, "East");
  850.         southPanel.setBorder(new TitledBorder(""));
  851.  
  852.         centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScroll,
  853.                 rightScroll);
  854.         centerSplit.setDividerLocation(100);
  855.  
  856.         frame = new JFrame("");
  857.         //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));  
  858.         frame.setLayout(new BorderLayout());
  859.         frame.add(northPanel, "North");
  860.         frame.add(centerSplit, "Center");
  861.         frame.add(southPanel, "South");
  862.         frame.setSize(600, 400);
  863.         int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
  864.         int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
  865.         frame.setLocation((screen_width - frame.getWidth()) / 2,
  866.                 (screen_height - frame.getHeight()) / 2);
  867.         frame.setVisible(true);
  868.     }
  869.  
  870.     //LOGIN
  871.     public boolean connectServer(int port, String hostIp, String name) {
  872.  
  873.         try {
  874.             socket = new Socket(hostIp, port);
  875.             out = new PrintWriter(socket.getOutputStream());
  876.             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  877.  
  878.             //LOGIN
  879.             // name@/x.x.x.x
  880.             sendMessage(name + "@" + socket.getLocalAddress().toString());
  881.  
  882.             //receive message
  883.             //receiveMessage = new ReceiveMessage(in, textArea);
  884.             receiveMessage = new ReceiveMessage();
  885.             receiveMessage.start();
  886.  
  887.             isConnected = true;
  888.             return true;
  889.  
  890.         } catch (Exception e) {
  891.             textArea.append("Server port: " + port + "Server IP: " + hostIp + "\r\n");
  892.             isConnected = false;
  893.             return false;
  894.         }
  895.     }
  896.  
  897.     @SuppressWarnings("deprecation")
  898.     public synchronized boolean closeConnection() {
  899.         try {
  900.            
  901.             sendMessage("CLOSE");
  902.             receiveMessage.stop(); //NullPointerException
  903.  
  904.             if (in != null) { in.close(); }
  905.             if (out != null) { out.close(); }
  906.             if (socket != null) { socket.close(); }
  907.  
  908.             isConnected = false;
  909.             return true;
  910.  
  911.         } catch (IOException e1) {
  912.             e1.printStackTrace();
  913.             isConnected = true;
  914.             return false;
  915.         }
  916.     }
  917.  
  918.     public void send() {
  919.         if (!isConnected) {
  920.             JOptionPane.showMessageDialog(frame, "Is not connected!", "",
  921.                     JOptionPane.ERROR_MESSAGE);
  922.             return;
  923.         }
  924.  
  925.         String message = textField.getText().trim();
  926.  
  927.         if (message == null || message.equals("")) {
  928.             JOptionPane.showMessageDialog(frame, "No message", "",
  929.                     JOptionPane.ERROR_MESSAGE);
  930.             return;
  931.         }
  932.  
  933.         // username@ALL@hello world
  934.         sendMessage(frame.getTitle() + "@" + "ALL" + "@" + message);
  935.  
  936.         textField.setText(null);
  937.     }
  938.  
  939.     public void sendMessage(String message) {
  940.  
  941.         out.println(message);
  942.         out.flush();
  943.     }
  944.  
  945.     class ReceiveMessage extends Thread {
  946.  
  947.         public void run() {
  948.             String msgFromServer = "";
  949.             while (true) {
  950.                 try {
  951.                    
  952.                     // => CLOSE, ADD@, DELETE@, USERLIST@, MAX@, or username: hi
  953.                     msgFromServer = in.readLine();
  954.                     System.out.println(msgFromServer);
  955.  
  956.                     // '/' or, '@'
  957.                     StringTokenizer tok = new StringTokenizer(msgFromServer, "/@");
  958.  
  959.                     String command = tok.nextToken();
  960.  
  961.                     // CLOSE
  962.                     if (command.equals("CLOSE")) {
  963.                         textArea.append("Server closed!\r\n");
  964.                         removeUsers();
  965.                         return;
  966.                     }
  967.                     // MAX@username/x.x.x.x  
  968. //                    else if (command.equals("MAX")) {
  969. //                        textArea.append("Max limited!\r\n");
  970. //                        removeUsers();
  971. //                        return;
  972. //                    }
  973.                     // DELETE@username
  974.                     else if (command.equals("DELETE")) {
  975.  
  976.                         String username = tok.nextToken();
  977.  
  978.                         listModel.removeElement(username);
  979.                    
  980.                     // ADD@username/x.x.x.x  
  981.                     } else if (command.equals("ADD")) {
  982.                        
  983.                         String username = "";
  984.                         String userIp = "";
  985.                        
  986.                         if ((username = tok.nextToken()) != null
  987.                                 && (userIp = tok.nextToken()) != null) {
  988.                            
  989.                             listModel.addElement(username);
  990.                         }
  991.  
  992.                     // USERLIST@numOfUser@username@/x.x.x.x@username@/x.x.x.x        
  993.                     } else if (command.equals("USERLIST")) {
  994.  
  995.                         int numOfUser = Integer.parseInt(tok.nextToken());
  996.                         String username = null;
  997.                         String userIp = null;
  998.  
  999.                         for (int i = 0; i < numOfUser; i++) {
  1000.                             username = tok.nextToken();
  1001.                             userIp = tok.nextToken();
  1002.                            
  1003.                             listModel.addElement(username);
  1004.                         }
  1005.  
  1006.                     // username: hello world
  1007.                     } else {
  1008.                         textArea.append(msgFromServer + "\r\n");
  1009.                     }
  1010.                 } catch (IOException e) {
  1011.                     e.printStackTrace();
  1012.                 } catch (Exception e) {
  1013.                     e.printStackTrace();
  1014.                 }
  1015.             }
  1016.         }
  1017.  
  1018.         public synchronized void removeUsers() throws Exception {
  1019.  
  1020.             listModel.removeAllElements();
  1021.  
  1022.             if (in != null) { in.close(); }
  1023.             if (out != null) { out.close(); }
  1024.             if (socket != null) { socket.close(); }
  1025.             isConnected = false;
  1026.         }
  1027.     }  // end of ReceiveMessage class
  1028.    
  1029.     public static void main(String[] args) {
  1030.         new Client();
  1031.     }
  1032. }
Advertisement
Add Comment
Please, Sign In to add comment