Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

trouble java aplication chat, need help please

$
0
0
I made java aplication chat, but in this aplication cannot use to receive the message but can to send the message.. please help me to fix it...


import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import sun.applet.Main;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * server.java
 *
 * Created on 24-Dec-2012, 19:25:33
 */

/**
 *
 * @author tnt
 */
public class Chat extends javax.swing.JFrame implements ActionListener, Runnable{

    public static String hostIP = "localhost";
    public static int port = 1234;
    public static int user;
    public static int statusKoneksi = 0;
    public static int statusSiapKirim = 0;
    public static StringBuffer textMasuk = new StringBuffer("");
    public static StringBuffer textKeluar = new StringBuffer("");

   // TCP Components
   public static ServerSocket hostServer;
   public static Socket socket;
   public static BufferedReader in;
   public static BufferedWriter out;
   protected Thread th;

    /** Creates new form server */
    public Chat() {
       initComponents();
       actionPerformed(null);
    }

    /** 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();
        txtchat = new javax.swing.JTextArea();
        txtkirimchat = new javax.swing.JTextField();
        jToolBar1 = new javax.swing.JToolBar();
        lblstatus = new javax.swing.JLabel();
        txtstatususer = new javax.swing.JLabel();
        txtip = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtport = new javax.swing.JTextField();
        cbuser = new javax.swing.JComboBox();
        btnconnect = new javax.swing.JButton();
        btndisconnect = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        txtchat.setColumns(20);
        txtchat.setEditable(false);
        txtchat.setLineWrap(true);
        txtchat.setRows(5);
        txtchat.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(153, 204, 255), new java.awt.Color(204, 204, 255)));
        jScrollPane1.setViewportView(txtchat);

        txtkirimchat.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.blue, new java.awt.Color(153, 204, 255)));
        txtkirimchat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtkirimchatActionPerformed(evt);
            }
        });

        jToolBar1.setBackground(new java.awt.Color(255, 255, 255));
        jToolBar1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "status koneksi", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.DEFAULT_POSITION));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        lblstatus.setBackground(new java.awt.Color(255, 0, 0));
        lblstatus.setForeground(new java.awt.Color(255, 0, 0));
        lblstatus.setText("Disconnect");
        jToolBar1.add(lblstatus);
        jToolBar1.add(txtstatususer);

        txtip.setText("localhost");
        txtip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtipActionPerformed(evt);
            }
        });

        jLabel2.setText("IP : ");

        jLabel3.setText("PORT : ");

        txtport.setText("1234");

        cbuser.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Server", "Client" }));

        btnconnect.setText("Connect");
        btnconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnconnectActionPerformed(evt);
            }
        });

        btndisconnect.setText("Disconnect");
        btndisconnect.setEnabled(false);
        btndisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btndisconnectActionPerformed(evt);
            }
        });

        jLabel4.setText("Anda Sebagai : ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnconnect)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btndisconnect))
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                    .addComponent(txtport, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                    .addComponent(txtip, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(cbuser, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtkirimchat, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbuser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(43, 43, 43)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnconnect)
                            .addComponent(btndisconnect)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addComponent(txtkirimchat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>

    private void txtkirimchatActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
    }                                            

    private void txtipActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    public void actionPerformed(ActionEvent e) {
        add(txtkirimchat);
        txtkirimchat.addKeyListener(new KeyAdapter() {
         @Override
         public void keyPressed(KeyEvent e) {
           int key = e.getKeyCode();
           if (key == KeyEvent.VK_ENTER) {
               String s = txtkirimchat.getText();
               if (!s.equals("")) {
                   try{
                       out.write(s);
                       out.newLine();
                       out.flush();
                       txtchat.append("Aku : " + s + "\n");
                       txtkirimchat.selectAll();
                   }catch(IOException h){

                   }
                }
              }
           }
         }
      );
    }

    private void btnconnectActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here
        statusKoneksi = 1;
        rubahStatus(statusKoneksi);
            
           user = cbuser.getSelectedIndex();

           hostIP = txtip.getText();
           port = Integer.parseInt(txtport.getText());
                         try {
                                if(user == 0){
                                    //Jika yang masuk adalah server
                                   hostServer = new ServerSocket(port);
                                   socket = hostServer.accept();
                                   System.out.println("saya server");
                                }else{
                                    //Jika yang masuk adalah client
                                   socket = new Socket(hostIP, port);
                                   System.out.println("saya client");
                                }
                                //Membuka stream I/O dari socket yang sudah dibuka
                                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                                Thread th ;
                                th = new Thread();//this nya dihapus
                                out.write("terkoneksi");
                                out.newLine();
                                th.start();

                            }
                            catch (IOException e) {
                                    try {
                                        tutupKoneksi();
                                    } catch (IOException ex) {
                                        Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                            }
    }                                          
    public void run() {
        try {
            socket.setSoTimeout(100);
        } catch (Exception e) {
        }
        while (true) {
            try {
                txtchat.append("x: " + in.readLine() + "\n");
                System.out.println(in.readLine());
            } catch (Exception h) {
            }
        }
    }
    private void btndisconnectActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
        statusKoneksi = 0;
        rubahStatus(statusKoneksi);
        try {
            tutupKoneksi();
        } catch (IOException ex) {
            Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                             
    
    private static void tutupKoneksi() throws IOException {
      try {
         if (hostServer != null) {
            hostServer.close();
            hostServer = null;
         }
      }
      catch (IOException e) { hostServer = null; }

      try {
         if (socket != null) {
            socket.close();
            socket = null;
         }
      }
      catch (IOException e) { socket = null; }

      try {
         if (in != null) {
            in.close();
            in = null;
         }
      }
      catch (IOException e) { in = null; }

      if (out != null) {
         out.close();
         out = null;
      }
   }

    private void rubahStatus(int statusbaru){
    if(statusKoneksi == 0){
        btndisconnect.setEnabled(false);
        btnconnect.setEnabled(true);
        lblstatus.setText("Disconnect");
        lblstatus.setForeground(Color.red);
        txtstatususer.setVisible(false);
        txtip.setEnabled(true);
        txtport.setEnabled(true);
    }
    if(statusKoneksi == 1){
        btndisconnect.setEnabled(true);
        btnconnect.setEnabled(false);
        lblstatus.setText("Connected");
        lblstatus.setForeground(Color.blue);
        txtstatususer.setVisible(true);
        if(user == 0){
            txtstatususer.setText("                           Status : Server");
        }
        if(user == 1){
            txtstatususer.setText("                           Status : Client");
        }
        txtip.setEnabled(false);
        txtport.setEnabled(false);
    }
}
    
   /* private static void MasukChatBox(String s) {
      synchronized (textMasuk) {
         textMasuk.append(s);
      }
   }*/

   /* private static void sendString(String s) {
      synchronized (textKeluar) {
         textKeluar.append(s + "\n");
      }
   }*/

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                    new Chat().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnconnect;
    private javax.swing.JButton btndisconnect;
    private javax.swing.JComboBox cbuser;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblstatus;
    private javax.swing.JTextArea txtchat;
    private javax.swing.JTextField txtip;
    private javax.swing.JTextField txtkirimchat;
    private javax.swing.JTextField txtport;
    private javax.swing.JLabel txtstatususer;
    // End of variables declaration


}



Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>