Home > Pemrograman Java > Java: Contoh Server + Client Multi-Thread

Java: Contoh Server + Client Multi-Thread


Contoh server MultiEchoServer ini dapat menerima koneksi dan berinteraksi dengan banyak client pada satu waktu.

/*
 * Program MultiEchoServer
 * server dengan fitur multithread menerima message dari client
 * dan mengirimkannya kembali ke client
 */
package netprog2010;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class MultiEchoServer {

    private static ServerSocket serverSocket;
    private static final int PORT = 1234;

    public static void main(String[] args) throws IOException {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("Server berjalan, menunggu client...");
        } catch (IOException ioEx) {
            System.out.println("\nTidak dapat mensetup port!");
            System.exit(1);
        }
        do {
            //Menunggu koneksi dari client...
            Socket client = serverSocket.accept();
            System.out.println("\nClient baru diterima.\n");

            //Buat thread untuk menangani komunikasi dengan client ini
            //lewatkan socket yang relevan ke contructor dari  thread ini
            ClientHandler handler = new ClientHandler(client);
            handler.start();    //menjalankan thread yang telah dibuat
        } while (true);
    }
}

class ClientHandler extends Thread {

    private Socket client;
    private Scanner input;
    private PrintWriter output;

    public ClientHandler(Socket socket) {
        //Set up referensi ke socket yang beraosiasi...
        client = socket;
        try {
            input = new Scanner(client.getInputStream());
            output = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException ioEx) {
            //ioEx.printStackTrace();
        }
    }

    public void run() {
        String received;

        do {
            //Terima pesan dari client pada input stream socket...
            received = input.nextLine();
            System.out.println(received);

            //Echo-kan pesan kembali ke client pada stream output socket...
            output.println("[" + received + "]");

            //Ulangi sampai client mengirimkan pesan 'QUIT'...
        } while (!received.equals("QUIT"));
        
        try {
            if (client != null) {
                System.out.println("Menutup koneksi...");
                client.close();
            }
        } catch (IOException ioEx) {
            System.out.println("Penutupan koneksi gagal!");
        }
    }
}

Sedangkan client untuk memanfaatkan server tersebut, pada kelas MultiEchoClient, diperlihatkan pada kode berikut:

/*
 * Program MultiEchoClient
 * Digunakan untuk membangun koneksi ke server MultiEchoServer
 * Mengirimkan pesan teks ke server dan menerima balasannya
 */
package netprog2010;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class MultiEchoClient {

    private static InetAddress host;
    private static final int PORT = 1234;

    public static void main(String[] args) {
        try {
            host = InetAddress.getLocalHost();
        } catch (UnknownHostException uhEx) {
            System.out.println("\nHost ID tidak ditemukan!\n");
            System.exit(1);
        }
        sendMessages();
    }

    private static void sendMessages() {
        Socket socket = null;
        try {
            socket = new Socket(host, PORT);
            Scanner networkInput = new Scanner(socket.getInputStream());
            PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);

            //Set up stream untuk masukan dari keyboard...
            Scanner userEntry = new Scanner(System.in);
            String message, response;
            do {
                System.out.print("Masukkan pesan ('QUIT' untuk keluar): ");
                message = userEntry.nextLine();

                //Kirim pesan (message)ke server pada output stream socket...
                //Terima respon dari server pada stream input socket...
                networkOutput.println(message);
                response = networkInput.nextLine();

                //Tampilkan respon dari server...
                System.out.println("\nSERVER> " + response);
            } while (!message.equals("QUIT"));
        } catch (IOException ioEx) {
            //ioEx.printStackTrace();
        } finally {
            try {
                System.out.println("\nMenutup koneksi...");
                socket.close();
            } catch (IOException ioEx) {
                System.out.println("Gagal menutup koneksi!");
                System.exit(1);
            }
        }
    }
}

Selamat mencoba, semoga berfaedah🙂

  1. 27 November 2010 at 2:03 am

    yeah..i like it!

  2. dhekha
    18 November 2011 at 7:31 am

    Thanks a lot🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: