Selasa, 18 Februari 2014

Socket Programming Java

Setelah kita memelajari bagaimana membuat Socket Programming menggunakan bahasa pemrograman C, selanjutnya kita akan membuat Socket Programming menggunakan Java.

Apa yang harus disiapkan ?

Pertama-tama buatlah minimal 2 file ( 1 server dan 1 client ) menggunakan text editor.
Dalam hal ini saya buat file Provider.java sebagai server dan Requester.java sebagai client

Berikut ini isi dari Provider.java sebagai server

import java.io.*;
import java.net.*;
public class Provider{
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    Provider(){}
    void run()
    {
        try{
            //1. creating a server socket
            providerSocket = new ServerSocket(2004, 10);
            //2. Wait for connection
            System.out.println("Waiting for connection");
            connection = providerSocket.accept();
            System.out.println("Connection received from " + connection.getInetAddress().getHostName());
             //3. get Input and Output streams
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());
            sendMessage("Connection successful");
            //4. The two parts communicate via the input and output streams
            do{
                try{
                    message = (String)in.readObject();
                    System.out.println("client>" + message);
                    if (message.equals("bye"))
                        sendMessage("bye");
                }
                catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                }
            }while(!message.equals("bye"));
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                providerSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            System.out.println("server>" + msg);
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[])
    {
        Provider server = new Provider();
        while(true){
            server.run();
        }
    }
}


Berikut ini isi file Requester.java sebagai client

import java.io.*;
import java.net.*;
public class Requester{
    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    Requester(){}
    void run()
    {
        try{
            //1. creating a socket to connect to the server
            requestSocket = new Socket("localhost", 2004);
            System.out.println("Connected to localhost in port 2004");
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            //3: Communicating with the server
            do{
                try{
                    message = (String)in.readObject();
                    System.out.println("server>" + message);
                    sendMessage("Hi my server");
                    message = "bye";
                    sendMessage(message);
                }
                catch(ClassNotFoundException classNot){
                    System.err.println("data received in unknown format");
                }
            }while(!message.equals("bye"));
        }
        catch(UnknownHostException unknownHost){
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            System.out.println("client>" + msg);
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[])
    {
        Requester client = new Requester();
        client.run();
    }
}


Setelah memiliki file server dan client ?

Nah, sekarang kita akan melakukan compile dan run dengan step-step berikut:

1. Buka 2 terminal, 1 untuk server dan 1 lagi untuk client (jika hanya 1 client, tambah terminal jika lebih)


2. Masuk ke direktori file Provider.java dan Requester.java

Terminal 1

 
Terminal 2


3. Compile Provider.java di terminal 1

Terminal 1


4. Compile Requester.java di terminal 2

Terminal 2


5. Jalankan provider

Terminal 1


6. Jalankan requester

Terminal 2


7.Tampilan berikut menandakan bahwa sistem client-server telah berhasil dibuat

Terminal 1

 
Terminal 2


Itulah step-step yang dilakukan untuk membuat Socket Programming menggunakan bahasa pemrograman Java. Jika ingin menghasilkan sistem yang lebih kompleks, file Provider.java dan Requester.java dapat dimodifikasi sesuai kebutuhan.

Tidak ada komentar:

Posting Komentar