Home > Pemrograman Java > Java: Contoh Server + Client Single Thread

Java: Contoh Server + Client Single Thread


Kode dari server, pada kelas EchoServer, adalah sebagai berikut:

package netprog2010;

//Server yang meng-echoe kembali pesan dari client (TCP)
import java.io.*;
import java.net.*;
import java.util.*;

public class EchoServer {

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

    public static void main(String[] args) {
        System.out.println("Membuka port...\n");

        try {
            servSock = new ServerSocket(PORT);              //Langkah 1.
        } catch (IOException ioEx) {
            System.out.println("Tidak terhubung ke port!");
            System.exit(1);
        }

        do {
            handleClient();
        } while (true);
    }	// akhir dari metode main()

    private static void handleClient() {
        Socket link = null;                                     //Langkah 2.
        try {
            link = servSock.accept();                           // Langkah 2.
            Scanner input = new Scanner(link.getInputStream()); //Langkah 3
            PrintWriter output = new PrintWriter(link.getOutputStream(), true);

            int numMessages = 0;
            String message = input.nextLine(); 		// Langkah 4.

            while (!message.equals("QUIT")) {
                numMessages++;
                System.out.println("Pesan masuk [" + numMessages + "]: " + message);
                output.println("Pesan " + numMessages + ": " + message);
                message = input.nextLine();
            }

            output.println(numMessages + " pesan yang diterima.");
        } // akhir dari try
        catch (IOException ioEx) {
            //ioEx.printStackTrace();
        } finally {
            try {
                System.out.println("\nMenutup koneksi...");
                link.close(); // Langkah 5.
            } catch (IOException ioEx) {
                System.out.println("Gagal menutup koneksi!");
                System.exit(1);
            }
        } //akhir dari finally
    } // akhir dari handleClient()
} // akhir dari kelas TCPEchoServer

Sedangkan contoh client, diperlihatkan sebagai kelas EchoClient adalah

package netprog2010;

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

public class EchoClient {

    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("Host ID not found!");
            System.exit(1);
        }
        accessServer();
    } //akhir dari metode main()

    private static void accessServer() {
        Socket link = null; 				//Langkah 1.
        try {
            link = new Socket(host, PORT); 		//langkah 1.
            Scanner input = new Scanner(link.getInputStream()); 	//Langkah 2.
            PrintWriter output = new PrintWriter(link.getOutputStream(), true); //Langkah 2.

            //Set up stream untuk input dari keyboard
            Scanner userEntry = new Scanner(System.in);
            String message, response;

            do {
                System.out.print("Masukkan pesan (QUIT untuk keluar): ");
                message = userEntry.nextLine();
		output.println(message);        //Langkah 3.
		response = input.nextLine();    //Langkah 3.
		System.out.println("\nSERVER> " + response);
            } while (!message.equals("QUIT"));
        } catch (IOException ioEx) {
            //ioEx.printStackTrace();
        } finally {
            try {
                System.out.println("\nMenutup koneksi...");
                link.close(); 			//Langkah 4.
            } catch (IOException ioEx) {
                System.out.println("Gagal menutup koneksi!");
                System.exit(1);
            }
        }
    } //akhir metode accessServer
}  //akhir kelas TCPEchoClient

Semoga bermanfaat🙂

  1. No comments yet.
  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: