Chatting Client/Server Java

Kali ini saya akan memposting program java dalam chat client/server.  Tujuan program ini adalah agar anda chatting antara komputer dengan berbeda komputer menggunakan koneksi LAN. Tentunya dengan mennjalankan program ini, akan  tetapi program ini masih sederhana dan saya ambil dari buku First Deitel Education Java,
langsung saja kita masuk ke source code ya teman",,,,
Source code server yaitu:

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * @(#)Server.java
 *
 *
 * @author benjie danyael
 * @version 1.00 2013/12/14
 */


public class Server extends JFrame {
    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;
    private int counter = 1;
   
    //set up GUI
    public Server() {
        super("Server");
        Container container = getContentPane();
       
        //create enterField and register listener
        enterField = new JTextField();
        enterField.setEditable(false);
        enterField.addActionListener(
            new ActionListener() {
                //send message to client
                public void actionPerformed(ActionEvent event) {
                    sendData(event.getActionCommand() );
                    enterField.setText("");
                }
            });
            container.add(enterField, BorderLayout.NORTH);
            //create display area
            displayArea = new JTextArea();
            container.add(new JScrollPane(displayArea), BorderLayout.CENTER);
            setSize(300, 150);
            setVisible(true);
    }//End server constructor
   
    //set up adn run server
    public void runServer() {
        //set up server to receive connection: procces connection
        try {
            //step 1: Create s ServerSocket
            server = new ServerSocket(12345, 100);
            while (true) {
                try {
                    waitForConnection(); //wait for connection
                    getStream();         //get input & output strem
                    processConnection(); //process connection
                }
                //process EOFException when client closes connection
                catch (EOFException eofException) {
                    System.err.println("Server terminated connection");
                }
                finally {
                    closeConnection(); //close connection
                    ++counter;
                }
            } // end while
        } //end try
        // process problem with I/O
        catch(IOException ioException) {
            ioException.printStackTrace();
        }
            } //end method runServer
            //wait for connection to arrive, then display connection info
           
        private void waitForConnection() throws IOException {
            displayMessage("Waiting For Connection");
            connection = server.accept(); //allow server to accept connection
            displayMessage("Connection " + counter + "received from: "+ connection.getInetAddress().getHostName() );
        }
       
        //get stream to send and received data
        private void getStream() throws IOException {
            //set up output stream for objects
            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush(); //flush output buffer to send header information
           
            //set upt input stream for objects
            input = new ObjectInputStream(connection.getInputStream());
           
            displayMessage("\nGot I/O Stream\n");
        }
       
        //process connection with client
        private void processConnection() throws IOException {
            //send connection succesfull message to client
            String message = "Connection Succesful";
            sendData(message);
           
            //enable enterField to server user can send message
            setTextFieldEditable(true);
            do {//process message sent from client
           
            //read message and display it
            try {
                message = (String ) input.readObject();
                displayMessage("\n" +message);
            }
                //catch problem reading from client
                catch(ClassNotFoundException classNotFoundException) {
                    displayMessage("\nUnknown Object Type Received");
                }
               
            } while (!message.equals("CLIENT>>> TERMINATE"));
        }//end method processConnection
       
        //close stream and socket
        private void closeConnection() {
            displayMessage("\nTerminating Connection\n");
            setTextFieldEditable(false); //diseble enterField
           
            try {
                output.close();
                input.close();
                connection.close();
            }catch(IOException ioException) {
                ioException.printStackTrace();
            }
        }
       
        //send message to client
        private void sendData(String message) {
            //send object to client
            try {
                output.writeObject("SERVER>>> "+message);
                output.flush();
                displayMessage("\nSERVER>>> "+message);
            }
           
            //process problem sending object
            catch(IOException ioException) {
                displayArea.append("\nError Writing Object");
            }
        }
       
        //utility method called from other thread to manipulate
        //displayArea in the event-dispatch thread
        private void displayMessage(final String messageToDisplay) {
            //display message from event-dispatch thread of execution
            SwingUtilities.invokeLater(
                new Runnable() {
                     //inner class to ensure GUI updates properly
                   
                     public void run() { //updates displayArea
                         displayArea.append(messageToDisplay);
                         displayArea.setCaretPosition(
                             displayArea.getText().length() );
                     }
                }//end inner class
                );// end call to SwingUtilities.invokeLater
        }
       
        //utility method called from other threads to manipulate
        //enterField in the event-dipatch thread
        private void setTextFieldEditable(final boolean editable ) {
            //display message from event-dispatch thread of execution
            SwingUtilities.invokeLater(
                new Runnable() {//inner class to ensure GUI updates properly
               
                public void run() //set enterField's editability
                {
                    enterField.setEditable( editable);
                }
                   
                }//end nner class
                ); //end call to SwingUtilities.invokeLater
        }
       
        public static void main(String[] args) {
            Server application = new Server();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            application.runServer();
        }
} //end class server

dan source code untuk clientnya yaitu :

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * @(#)Client.java
 *
 *
 * @author benjie danyael
 * @version 1.00 2013/12/14
 */

public class Client extends JFrame {
    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String chatServer;
    private Socket client;
   
    //initialize chatServer and set Up GUI
    public Client (String host) {
        super ("Client: ");
        chatServer = host;
        Container container = getContentPane();
       
        //create enterFiled and register listener
        enterField = new JTextField();
        enterField.setEditable(false);
        enterField.addActionListener(
            new ActionListener() {
                //send message to server
                public void actionPerformed(ActionEvent event) {
                    sendData(event.getActionCommand() );
                    enterField.setText("");
                }
            }
            );
            container.add(enterField, BorderLayout.NORTH);
           
            //create displayArea
            displayArea = new JTextArea();
            container.add(new JScrollPane(displayArea), BorderLayout.CENTER);
            setSize(300, 150);
            setVisible(true);
    }//end client constructor
   
    //connect to server and process messages from server
    private void runClient() {
        //connect to server, get streams, process connection
        try {
            connectToServer(); //create a socket to make connection
            getStreams(); //get the input and output streams
            processConnection(); //process connection
        }
       
        //server closed connection
        catch(EOFException eofException) {
            System.err.println("Client Terminated Connection");
        }
        //process problems communicating with server
        catch(IOException ioException) {
            ioException.printStackTrace();
        }
        finally {
            closeConnection(); //close connection
        }
    } //end method runClient
   
    //connect to server
    private void connectToServer() throws IOException {
        displayMessage("Attempting Connection\n");
        //create Socket to make Connection to server
        client = new Socket(InetAddress.getByName(chatServer),12345);
        //display connection information
        displayMessage("Connet To: "+ client.getInetAddress().getHostName());
    }
   
    //get stream to send and received data
    private void getStreams() throws IOException {
        //set up output stream for object
        output = new ObjectOutputStream(client.getOutputStream());
        output.flush(); //flush output buffer to send header information
       
        //set up input stream for object
        input = new ObjectInputStream(client.getInputStream());
        displayMessage("\nGot I/O stream\n");
    }
   
    //process connection with server
    private void processConnection() throws IOException  {
        //enable enterField so client user can send messages
        setTextFieldEditable(true);
        do {//process messages sent from server
        //read messages and display it
        try {
            message = (String) input.readObject();
            displayMessage("\n" +message);
        }//catch problem reading from server
        catch(ClassNotFoundException classNotFoundException) {
            displayMessage("\nUnknown Object Type Received");
        }
        } while (!message.equals("SERVER>>> TERMINATE"));
    }//end method processConnection
   
    //close stream and socket
    private void closeConnection() {
        displayMessage("\nClosing Connection");
        setTextFieldEditable(false); //disable enterFiedl
        try {
            output.close();
            input.close();
            client.close();
        }catch(IOException ioException) {
            ioException.printStackTrace();
        }
    }
   
    //send message to server
    private void sendData(String message) {
        //send object to server
        try {
            output.writeObject("CLIENT>>> "+message);
            output.flush();
            displayMessage("\nCLIENT>>> "+message);
        }
       
        //process problem sending object
        catch(IOException ioException) {
            displayArea.append("\nError Writing Object");
        }
    }
   
    //Utility method called from other threads to manipulate
    //displayArea in the event-dispatch thread
    private void displayMessage(final String messageToDisplay) {
        //display message from GUI thread of execution
        SwingUtilities.invokeLater(
            new Runnable() { //inner class to ensure GUI updates properly
            public void run() //updates displayArea
            {
                displayArea.append(messageToDisplay);
                displayArea.setCaretPosition(
                    displayArea.getText().length());
            }
            } //end inner class
            ); //end call to SwingUtilities.invokeLater
    }
   
    //utility method called from other thread to manipulate
    //enterField in the event-dispacth thread
    private void setTextFieldEditable(final boolean editable) {
        //display message from GUI thread of execution
        SwingUtilities.invokeLater(
            new Runnable() { //inner class to ensure GUI updates properly
            public void run() { //sets enterField's editability
            enterField.setEditable(editable);
            }
            }//end inner class
            ); //end call to SwingUtilities.onvokeLater
    }
   
    public static void main(String[] args) {
        Client application;
        if(args.length == 0)
            application = new Client("127.0.0.1");
            else
                application = new Client(args[0]);
                application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                application.runClient();
    }
}//end class client

Hasil running untuk server sebelum client dirunning yaitu:

hasil running server setelah client dijalakan yaitu:

dan hasil running client yaitu:

nah,,,sekarang anda boleh chatting dengan teman anda menggunakan program java ini dengan koneksi kabel LAN,
selamat mencoba,,,
Tuhan Memberkati...
(Silahkan Tinggalkan Kritik Dan Saran Anda...)

Comments