Pages

Jumat, 22 Juli 2011

Chat Sederhana dengan Java Swing (GUI)

Penulis pernah membaca sebuah artikel tentang pembuatan program chatting dengan Java. Hanya saja, di artikel tersebut program chatting berupa text mode (bukan GUI) dan bersifat searah.

Terinspirasi ide tersebut, penulis mencoba membuat program chat sederhana berbasis GUI menggunakan Java Swing dan bersifat dua arah.

Di sini, chatting dilakukan oleh dua PC, yaitu:

1. PC bulan dengan IP Address 10.1.1.1
Program yang ada di PC ini ChatServer.java. Program ini dijalankan dulu, karena bersifat stand by menunggu koneksi dari client.

2. PC matahari dengan IP Address 10.1.1.2
Program yang ada di PC ini ChatClient.java. Ketika program ini dijalankan, klik button "Open Connection", maka akan muncul input dialog yang meminta isian IP Address Chat Server yang harus dihubungi (di kasus ini diisi 10.1.1.1, sesuai IP Address ChatServer)).

Sebenarnya, tes kedua program ini bisa dilakukan di 1 (satu) PC. Namun, agar lebih terlihat nyata, maka di contoh ini dilakukan di 2 PC.

1. PC bulan (10.1.1.1)

1.1. Source code ChatServer.java
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ChatServer extends JFrame{

JLabel lblPesan =  new JLabel  ("Kirim Pesan :");
TextArea taPesan=new TextArea(4,50);
JLabel lblBalasan = new JLabel ("Dari Teman  :");
TextArea taTeman=new TextArea(4,50);
JButton btnSend=new JButton("Send");
JButton btnClose=new JButton("Close Connection");
ServerSocket sktServer;
Socket conClient;

ObjectInputStream fromClient;
ObjectOutputStream toClient;
String s=null;
Container c;
   

public void sendData(){
           try{
                       toClient=new ObjectOutputStream(conClient.getOutputStream());
                       toClient.writeObject(taPesan.getText());
                       System.out.println(taPesan.getText());
                       taPesan.setText("");
               taPesan.requestFocus();
              
           }
           catch (EOFException ex){
                       ;
           }
           catch(NullPointerException npe){
                     JOptionPane.showMessageDialog(null, "Koneksi Belum Tersambung ! ",
                                 "Pesan", JOptionPane.ERROR_MESSAGE);
           }
           catch(SocketException se){
                     JOptionPane.showMessageDialog(null, "Koneksi Putus !",
                                 "Pesan", JOptionPane.ERROR_MESSAGE);
           }
           catch(IOException io){
                       System.out.println("IO Exception");
                       io.printStackTrace();
           }
}//end void sendData()


public void closeConnection(){
           try{
                     //toClient.writeObject("bye");
                     conClient.close();
                     conClient=null;
                     System.exit(0);
           }//end try
           catch (EOFException ex){
                       ;
           }
           catch(IOException io){
                       System.out.println("IO Exception");
                       io.printStackTrace();
           }
}//end closeConnection();

public ChatServer()throws IOException{
                     c = getContentPane();
                     c.setLayout (new FlowLayout());
                     c.add (lblPesan);
                     c.add (taPesan);
                     c.add (lblBalasan);
                     c.add (taTeman);
                     c.add (btnSend);
                     c.add (btnClose);
                         

           btnSend.addActionListener (new ActionListener(){
                       public void actionPerformed(ActionEvent evt){
                                   sendData();
                       }//end void actionPerformed
           });

           btnClose.addActionListener (new ActionListener(){
                       public void actionPerformed(ActionEvent evt){
                                   closeConnection();
                       }//end void actionPerformed
           });

}//end public ChatServer()

         public void terimaKoneksi() throws IOException{
             //sktServer=new ServerSocket(2000,1000);
                     sktServer=new ServerSocket(2000);
                     conClient=sktServer.accept();
                     //tunggu sampai client masuk melalui port 2000

                     //System.out.println("Tersambung dengan client " +
                                 //conClient.getInetAddress());

                     JOptionPane.showMessageDialog(null, "Tersambung dengan Client " +
                                 conClient.getInetAddress().toString(), "Pesan",
                                 JOptionPane.INFORMATION_MESSAGE);
                     sktServer.close();
 
                     try{
                                                 
                                 fromClient=new ObjectInputStream(conClient.getInputStream());
                                 do{
                                             try{
                                                         s=(String) fromClient.readObject();
                                                         //System.out.println(s);
                                                         taTeman.setText(s);
                                             }//end try
                                             catch(ClassNotFoundException ex){
                                                         System.out.println("Error");
                                             }//end catch
                                 }//end do
                                 while (!s.equals("bye"));
                     }//end try
                     catch (EOFException ex){
                                 ;
                     }
                     catch (IOException io) {
                                 System.out.println("IO Exception");
                                 io.printStackTrace();
                     }
                     finally {
                                 System.out.println("Closed");
                                 conClient.close();
                     }//end finally
         }//end void terimaKoneksi()

         public static void main(String[] args) throws IOException
         {
                     ChatServer svr = new ChatServer();
                     svr.setTitle("Chatting - Server");
                     svr.setLocation (300,300);
                     svr.setSize(500,250);
                     svr.setVisible(true);           
                     svr.addWindowListener(new WindowAdapter(){
                                 public void windowClosing(WindowEvent ev){                                
                                             System.exit(0);
                                 }//end void
                     });
                     //supaya GUI muncul dulu & bisa terima koneksi, maka
                     //method terimaKoneksi() diletakkan di sini
                     svr.terimaKoneksi();

         }//end main
}//end class

1.2 Compile dan jalankan ChatServer

C:\> javac ChatServer.java

C:\> java ChatServe


Program ini stand by, menunggu koneksi dari ChatClient.

2. PC matahari (10.1.1.2)

2.1. Source code ChatClient.java
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ChatClient extends JFrame{

JLabel lblPesan =  new JLabel  ("Kirim Pesan :");
TextArea taPesan=new TextArea(4,50);
JLabel lblBalasan = new JLabel ("Dari Teman  :");
TextArea taBalasan=new TextArea(4,50);
JButton btnSend=new JButton("Send");
JButton btnOpen=new JButton("Open Connection");
JButton btnClose=new JButton("Close Connection");
Socket con=null;
ObjectOutputStream toServer;
ObjectInputStream fromServer;
String balasan=null;
String inputIPServer;

public void openConnection(){
           try{
                     //input dialog u/ memasukkan IP Address Chat Server
                     inputIPServer=JOptionPane.showInputDialog("Inputkan IP Server");

                     //koneksi ke port 2000 pada IP Address Server
                     con=new Socket(InetAddress.getByName(inputIPServer),2000);
                     toServer=new ObjectOutputStream(con.getOutputStream());
           }//end try
           catch (EOFException ex){
                       ;
           }
           catch(IOException io){
                       System.out.println("IO Exception");
                       io.printStackTrace();
           }
}//end openConnection();

public void sendData(){
           try{
                       toServer.writeObject(taPesan.getText());
                       taPesan.setText("");
               taPesan.requestFocus();
           }
           catch (EOFException ex){
                       ;
           }
           catch(IOException io){
                       System.out.println("IO Exception");
                       io.printStackTrace();
           }
}//end void sendData()

public void getData(){
           try{
                       fromServer=new ObjectInputStream(con.getInputStream());
                       balasan=(String) fromServer.readObject();
                       //System.out.println(balasan);
                       taBalasan.setText(balasan);
           }
           catch (ClassNotFoundException ex){
                       System.out.println("Error");
           }
           catch (EOFException ex){
                       ;
           }
           catch(IOException io){
                       System.out.println("IO Exception");
                       io.printStackTrace();
           }
}//end void getData()
public void closeConnection(){
           try{
                     toServer.writeObject("bye");
                     con.close();
                     con=null;
           }//end try
           catch (EOFException ex){
                       ;
           }
           catch(IOException io){
                       System.out.println("IO Exception");
                       io.printStackTrace();
           }
}//end closeConnection();

public ChatClient(){
           Container c = getContentPane();
           c.setLayout (new FlowLayout());
           c.add (lblPesan);
           c.add (taPesan);
           c.add (lblBalasan);
           c.add (taBalasan);
           c.add (btnOpen);
           c.add (btnSend);
           c.add (btnClose);

           btnOpen.addActionListener (new ActionListener(){
                       public void actionPerformed(ActionEvent evt){
                                   openConnection();
                       }//end void actionPerformed
           });

           btnSend.addActionListener (new ActionListener(){
                       public void actionPerformed(ActionEvent evt){
                                   sendData();
                                   getData();
                       }//end void actionPerformed
           });

           btnClose.addActionListener (new ActionListener(){
                       public void actionPerformed(ActionEvent evt){
                                   closeConnection();
                       }//end void actionPerformed
           });
   
           //pack();
}//end public ChatClient()

         public static void main(String[] args)
         {
                     ChatClient klien = new ChatClient();
                     klien.setTitle("Chatting - Client");
                     klien.setLocation (300,300);
                     klien.setSize(500,250);
                     klien.setVisible(true);         
                     klien.addWindowListener(new WindowAdapter(){
                                 public void windowClosing(WindowEvent ev){                                
                                             System.exit(0);
                                 }//end void
                     });

         }//main
}//class

2.2 Compile dan jalankan ChatClient

C:\> javac ChatClient.java

C:\> java ChatClient

Klik tombol "Open Connection", akan muncul input dialog untuk memasukkan IP Address ChatServer (10.1.1.1). Klik "OK"
Di PC bulan (ChatServer) muncul pesan "Tersambung dengan Client/10.1.1.2"


Klik "OK". Chatting bisa dimulai. Ketik di text box "Kirim Pesan" lalu klik tombol "Send". Hal yang sama dilakukan di kedua PC. Pesan dari teman chat akan muncul di text box "Dari Teman".

Misal, dari PC matahari (ChatClient) menulis pesan, "hai rek… lagi sibuk ta…?" lalu diklik tombol "Send". Di PC bulan (ChatServer) 


Bila PC bulan ingin menjawab, cukup ketik di text box "Kirim Pesan" lalu klik tombol "Send", begitu seterusnya. Misal akan dijawab, "ngga… ada apa…?" Di PC matahari (10.1.1.2) 

sumber : Achmad Faisol

1 komentar:

kvanjava1 mengatakan...

ini aapaan contoh GUI mana GUi nya z.z..z.z.z.

Posting Komentar