Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package chat.com.client; import java.awt.Component; import java.awt.PopupMenu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * * @author anhnghiammk */ public class ChatClient extends javax.swing.JFrame { private Socket socket; private InputStreamReader inReader; private BufferedReader buffReader; private PrintWriter writer; private String id; /** * Creates new form ChatClient */ public ChatClient() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaChat = new javax.swing.JTextArea(); jButtonSend = new javax.swing.JButton(); jTextFieldMessage = new javax.swing.JTextField(); jComboBoxListUser = new javax.swing.JComboBox(); jButtonConnect = new javax.swing.JButton(); jTextFieldAddress = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jTextAreaChat.setColumns(20); jTextAreaChat.setFont(new java.awt.Font("Consolas", 0, 13)); // NOI18N jTextAreaChat.setRows(5); jScrollPane1.setViewportView(jTextAreaChat); jButtonSend.setText("Send"); jButtonSend.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSendActionPerformed(evt); } }); jComboBoxListUser.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "all" })); jComboBoxListUser.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBoxListUserItemStateChanged(evt); } }); jButtonConnect.setText("Connect"); jButtonConnect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonConnectActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addComponent(jTextFieldMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBoxListUser, 0, 63, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonSend)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(jTextFieldAddress) .addGap(18, 18, 18).addComponent(jButtonConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(7, 7, 7).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonConnect) .addGroup(layout.createSequentialGroup().addGap(1, 1, 1).addComponent(jTextFieldAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(19, 19, 19) .addComponent(jTextFieldMessage)) .addGroup(layout.createSequentialGroup().addGap(18, 18, 18) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonSend, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE) .addComponent(jComboBoxListUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap())); pack(); }// </editor-fold> private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt) { String to = jTextFieldAddress.getText().trim(); String message = jTextFieldMessage.getText(); JSONObject jsonSendMess = new JSONObject(); jsonSendMess.put("id", id); jsonSendMess.put("to", to); jsonSendMess.put("message", message); jsonSendMess.put("type", "chat"); String json = jsonSendMess.toString(); writer.println(json); writer.flush(); System.out.println(message); jTextFieldMessage.setText(""); jTextAreaChat.append(message + " send: " + to + '\n'); } private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) { (new Listener()).start(); } private void jComboBoxListUserItemStateChanged(java.awt.event.ItemEvent evt) { // TODO add your handling code here: String name = (String) jComboBoxListUser.getSelectedItem(); jTextFieldAddress.setText(name); } private void formWindowClosing(java.awt.event.WindowEvent evt) { JSONObject jsonClientOut = new JSONObject(); jsonClientOut.put("id", id); jsonClientOut.put("type", "clientout"); String json = jsonClientOut.toString(); writer.print(json); writer.flush(); try { socket.close(); } catch (IOException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } System.exit(0); } protected class Listener extends Thread { @Override public void run() { try { socket = new Socket("localhost", 2222); inReader = new InputStreamReader(socket.getInputStream()); buffReader = new BufferedReader(inReader); writer = new PrintWriter(socket.getOutputStream()); Thread thread = new Thread(new Runnable() { @Override public void run() { try { String msg = null; while ((msg = buffReader.readLine()) != null) { typeChat(msg); } } catch (IOException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } } }); thread.start(); } catch (IOException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } jButtonConnect.setEnabled(false); } } private void typeChat(String msg) { try { JSONParser jsonParser = new JSONParser(); JSONObject jsontypeChat = (JSONObject) jsonParser.parse(msg); // jTextAreaChat.append(msg + '\n'); String type = jsontypeChat.get("type").toString(); if (type.equals("me")) { // get id for user id = jsontypeChat.get("id").toString(); jTextAreaChat.append(id + '\n'); } else if (type.equals("userOnline")) { // add item JSONArray jsonArray = (JSONArray) jsontypeChat.get("listUser"); jComboBoxListUser.removeAllItems(); jComboBoxListUser.addItem("all"); for (int i = 0; i < jsonArray.size(); i++) { if (!jsonArray.get(i).equals(id)) { // jComboBoxListUser.addItem(jsonArray.get(i)); } } } else { //(type.equals("chat")) String idWho = (String) jsontypeChat.get("id"); String message = (String) jsontypeChat.get("message"); jTextAreaChat.append(idWho + " say: " + message + '\n'); } } catch (ParseException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Metal".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ChatClient().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButtonConnect; private javax.swing.JButton jButtonSend; private javax.swing.JComboBox jComboBoxListUser; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextAreaChat; private javax.swing.JTextField jTextFieldAddress; private javax.swing.JTextField jTextFieldMessage; // End of variables declaration }