Monday, April 16, 2012

Java Socket Programming chat client - server

Pada artiket sebelumnya kita udah bahas mengenai pengertian socket nah untuk sekarang kita mulai ke coding. disini tujuan kita adalah membuat suatu aplikasi chating antara clietn dengan server. Bahasa yang digunakan pada pembahasan kali ini adalah bahasa pemrogramman java.
Untuk mempersingkat mari kita langsung saja masuk ke codeing. dalam pemrogramman socket kali ini kita butuh 2 source code, yang pertama yaitu source untuk server dan yang kedua source untuk client.

1. Source Server.


import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import java.io.PrintWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
public class ChatServer {
  private static final int PORT = 9001;
  private static HashSet names = new HashSet();
n  private static HashSet writers = new
HashSet();
  public static void main(String[] args) throws Exception {
     System.out.println("The chat server is running.");
     ServerSocket listener = new ServerSocket(PORT);
     try {
        while (true) {
           new Handler(listener.accept()).start();
        }
     } finally {
        listener.close();
     }
  }
  private static class Handler extends Thread {
     private String name;
     private Socket socket;
     private BufferedReader in;
     private PrintWriter out;
     public Handler(Socket socket) {
        this.socket = socket;
     }
     public void run() {
        try {
   //say_arifin@yahoo.com
   ;// Create character streams for the socket.
   in = new BufferedReader(new InputStreamReader(
       socket.getInputStream()));
   out = new PrintWriter(socket.getOutputStream(), true);
   // Request a name from this client. Keep requesting until
   // a name is submitted that is not already used. Note that
   // checking for the existence of a name and adding the name
   // must be done whhle locking the set of names.
   while (true) {
       out.println("SUBMITNAME");
       name = in.readLine();
       if (name == null) {
          return;
       }
       synchronized (names) {
          if (!names.contains(name)) {
             names.add(name);
             break;
          }
       }
   }
   // Now that a successful name has been chosen, add the
   // socket's print writer to the set of all writers so
   // this client can receive broadcast messages.
   out.println("NAMEACCEPTED");
   writers.add(out);
   // Accept messages from this client and broadcast them.
   // Ignore other clients that cannot be broadcasted to.
   while (true) {
       String input = in.readLine();
       if (input == null) {
          return;
       }
       for (PrintWriter writer : writers) {
          writer.println("MESSAGE " + name + ": " + input);
       }
   }
} catch (IOException e) {
   System.out.println(e);
} finally {
   // This client is going down! Remove its name and its print
   // writer from the sets, and close its socket.
   if (name != null) {
       names.remove(name);
        //say_arifin@yahoo.com
        }
        if (out != null) {
           writers.remove(out);
        }
        try {
           socket.close();
        } catch (IOException e) {
        }
      }
    }
  }
}

Oke source untuk server kurang lebihnya seperti yang di atas, untuk selanjutnya kita coding clientnya.
2. Source code Client
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ChatClient {
  BufferedReader in;
  PrintWriter out;
  JFrame frame = new JFrame("Chatter");
  JTextField textField = new JTextField(40);
  JTextArea messageArea = new JTextArea(8, 40);
  public ChatClient() {
     // Layout GUI
     textField.setEditable(false);
     messageArea.setEditable(false);
     frame.getContentPane().add(textField, "North");
     frame.getContentPane().add(new JScrollPane(messageArea),
"Center");
     frame.pack();
     // Add Listeners
     textField.addActionListener(new ActionListener() {
                                                     //say_arifin@yahoo.com
      /**
       * Responds to pressing the enter key in the textfield by sending
       * the contents of the text field to the server. Then clear
       * the text area in preparation for the next message.
       */
      public void actionPerformed(ActionEvent e) {
         out.println(textField.getText());
         textField.setText("");
      }
   });
}
/**
 * Prompt for and return the address of the server.
 */
private String getServerAddress() {
   return JOptionPane.showInputDialog(
      frame,
      "Enter IP Address of the Server:",
      "Welcome to the Chatter",
      JOptionPane.QUESTION_MESSAGE);
}
/**
 * Prompt for and return the desired screen name.
 */
private String getName() {
   return JOptionPane.showInputDialog(
      frame,
      "Choose a screen name:",
      "Screen name selection",
      JOptionPane.PLAIN_MESSAGE);
}
/**
 * Connects to the server then enters the processing loop.
 */
private void run() throws IOException {
   // Make connection and initialize streams
   String serverAddress = getServerAddress();
   Socket socket = new Socket(serverAddress, 9001);
   in = new BufferedReader(new InputStreamReader(
      socket.getInputStream()));
   out = new PrintWriter(socket.getOutputStream(), true);
   // Procers all messages from server, according to the protocol.
   :while (true) {
                   //say_arifin@yahoo.com
        String line = in.readLine();
        if (line.startsWith("SUBMITNAME")) {
           out.println(getName());
        } else if (line.startsWith("NAMEACCEPTED")) {
           textField.setEditable(true);
        } else if (line.startsWith("MESSAGE")) {
           messageArea.append(line.substring(8) + "\n");
        }
     }
  }
  /**
   * Runs the client as an application with a closeable frame.
   */
  public static void main(String[] args) throws Exception {
     ChatClient client = new ChatClient();
     client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     client.frame.setVisible(true);
     client.run();
  }
}

Untuk Uji coba silahkan anda jalankan / compile source server terlebih dahulu dan kemudian run source clientnya. ok selamat mencoba dan semoga berhasil.

0 komentar:

Post a Comment