Recent Posts

Jumat, 06 Maret 2015

Membuat Aplikasi Chatting Di Java (Netbeans)

Source Code untuk membuat Client Server pada Java, Ini dia Kodingnya :)


/*
 * 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 pkg1410530244_clientserverhandra;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
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.JOptionPane;

/**
 *
 * @author HANDRA
 */
public class ClientServer extends javax.swing.JFrame implements  Runnable{
    Socket client;
    ServerSocket server;
    BufferedReader Server_Reader, Client_Reader;
    BufferedWriter Server_Writer, Client_Writer;
   
    /**
     * Creates new form ClientServer
     */
    public ClientServer() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jCBServer = new javax.swing.JComboBox();
        jBtOn = new javax.swing.JButton();
        jBtAbout = new javax.swing.JButton();
        jtxtUsername = new javax.swing.JTextField();
        LChat = new java.awt.List();
        jtxtChat = new javax.swing.JTextField();
        jBtSend = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jBtClear = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jCBServer.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jCBServer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Server", "Client" }));
        jCBServer.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jCBServerItemStateChanged(evt);
            }
        });

        jBtOn.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jBtOn.setText("ON");
        jBtOn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtOnActionPerformed(evt);
            }
        });

        jBtAbout.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jBtAbout.setText("ABOUT");
        jBtAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtAboutActionPerformed(evt);
            }
        });

        jtxtUsername.setFont(new java.awt.Font("Times New Roman", 0, 11)); // NOI18N
        jtxtUsername.setText("USERNAME");
        jtxtUsername.setFocusable(false);

        LChat.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N

        jtxtChat.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jtxtChat.setText("Insert Message Here");
        jtxtChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtxtChatActionPerformed(evt);
            }
        });

        jBtSend.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        jBtSend.setText("SEND");
        jBtSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtSendActionPerformed(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton1.setText("HELP");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jBtClear.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        jBtClear.setText("CLEAR");
        jBtClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtClearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jtxtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxtChat, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(LChat, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jBtSend, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(jBtClear, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(27, Short.MAX_VALUE))))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCBServer, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jBtOn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBtAbout)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jBtAbout, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jBtOn, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
                            .addComponent(jCBServer, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))))
                .addGap(18, 18, 18)
                .addComponent(jtxtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(LChat, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(94, 94, 94)
                        .addComponent(jBtClear, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtChat, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtSend, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("APLIKASI CHATING");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void client_connection(){
        try{
            String ip = JOptionPane.showInputDialog("Masukkan IP Address");
            client = new Socket(ip,2000);
            jCBServer.setEnabled(false);
            Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            Server_Writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
            jBtOn.setText("Disconnect");
        }catch(UnknownHostException ex){
            System.out.println("Accept Failed");
            System.exit(-1);
        }catch(IOException ex){
            Logger.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
    private void read_connection(){
        try{
            try{
                try{
                    server = new ServerSocket(2000);
                    this.setTitle("Please Wait...");
                }catch(IOException ex){
                    System.out.println("Could not  listen");
                    System.exit(-1);
                }
                client = server.accept();
                this.setTitle("Connected" + client.getInetAddress());
            }catch(IOException ex){
                System.out.println("Accept Failed");
                System.exit(-1);
            }
            Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            Server_Writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
        }catch(IOException ex){
            System.out.println("Read Failed");
            System.exit(-1);
        }
    }
   
    private void disconnected_by_client(){
        try{
            client.close();
            Server_Reader.close();
            Server_Writer.close();
            jCBServer.setEnabled(true);
            jBtOn.setText("Connect");
        }catch(IOException ex){
            Logger.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
    private void stopped_by_server(){
        try{
            Server_Reader.close();
            Server_Writer.close();
            jBtOn.setText(" O N");
            setTitle("Disconnect");
        }catch(IOException ex){
            Logger.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
    private void jBtOnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtOnActionPerformed
        if(jBtOn.getText().equals("Connect")){
            jBtOn.setText("Disconnect");
            client_connection();
            Thread thread = new Thread(this);
            thread.start();
        }else if (jCBServer.getSelectedItem().equals("Server")){
            jBtOn.setText("O F F");
            read_connection();
            Thread thread = new Thread(this);
            thread.start();
        }         
       
    }//GEN-LAST:event_jBtOnActionPerformed

    private void jBtAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtAboutActionPerformed
       new About().setVisible(true);
    }//GEN-LAST:event_jBtAboutActionPerformed

    private void jBtSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtSendActionPerformed
        try {
            Server_Writer.write(jtxtUsername.getText() + " : " + jtxtChat.getText());
            Server_Writer.newLine();
            Server_Writer.flush();
        }catch(IOException ex){
            Logger.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        LChat.add("Me : " +  jtxtChat.getText());
        jtxtChat.setText(" ");
    }//GEN-LAST:event_jBtSendActionPerformed

    private void jCBServerItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCBServerItemStateChanged
        if (jCBServer.getSelectedItem().equals("Server")){
            jBtOn.setText("O N");
            jtxtUsername.setText("Server");
        }else{
            jBtOn.setText("Connect");
            jtxtUsername.setText("Client");
        }
    }//GEN-LAST:event_jCBServerItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        new Help().setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jBtClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtClearActionPerformed
        LChat.removeAll();
    }//GEN-LAST:event_jBtClearActionPerformed

    private void jtxtChatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxtChatActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtxtChatActionPerformed

    /**
     * @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 ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientServer.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 ClientServer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.List LChat;
    private javax.swing.JButton jBtAbout;
    private javax.swing.JButton jBtClear;
    private javax.swing.JButton jBtOn;
    private javax.swing.JButton jBtSend;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jCBServer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jtxtChat;
    private javax.swing.JTextField jtxtUsername;
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
       while(true){
           try {
               LChat.add(Server_Reader.readLine());
           } catch (IOException ex) {
               Logger.getLogger(ClientServer.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
    }
}




Berikut adalah Hasil Dari program Client Server



0 komentar:

Posting Komentar