SlideShare a Scribd company logo
Distributed Programming, 10 November 2011
   UDP
       Low-level, connectionless
       No reliability guarantee
   TCP
       Connection-oriented
       Not as efficient as UDP




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   2
     The sending/receiving point-
        Class DatagramSocket
          void close() : close a datagram socket
          int getLocalPort() : returns the port number on which
           socket is bound
          InetAddress getLocalAddress() : returns the local
           address to which the socket is bound
          void receive(DatagramPacket p) : blocks until a
           datagram is received and the packet’s buffer contains the data
           received
          void send(DatagramPacket p) : sends a datagram
           packet from this socket




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)                   3
//Datagram Server
   public class DatagramServer {
       public static void main(String[] args) {
           DatagramPacket datapacket, returnpacket;
           int port = 2018;
           int len = 1024;
           try {
               DatagramSocket datasocket = new DatagramSocket(port);
               byte[] buf = new byte[len];
               datapacket = new DatagramPacket(buf, buf.length);
               while (true) {
                   try {
                       datasocket.receive(datapacket);
                       returnpacket = new DatagramPacket(
                               datapacket.getData(),
                               datapacket.getLength(),
                               datapacket.getAddress(),
                               datapacket.getPort());
                       datasocket.send(returnpacket);
                   } catch (IOException e) {
                       System.err.println(e);
                   }
               }
           } catch (SocketException se) {
               System.err.println(se);
           }
       }
   }




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)              4
//Datagram Client
public class DatagramClient {
    public static void main(String[] args) {
        String hostname;
        int port = 2018;
        int len = 1024;
        DatagramPacket sPacket, rPacket;
        InetAddress ia = InetAddress.getByName(hostname);
            DatagramSocket datasocket = new DatagramSocket();
            BufferedReader stdinp = new BufferedReader(
                                         new InputStreamReader(System.in));
            while (true) {
              String echoline = stdinp.readLine();
                    if (echoline.equals("done")) break;
                    byte[] buffer = new byte[echoline.length()];
                    buffer = echoline.getBytes();
                    sPacket = new DatagramPacket(buffer, buffer.length, ia,
                                   port);
                    datasocket.send(sPacket);
                    byte[] rbuffer = new byte[len];
                    rPacket = new DatagramPacket(rbuffer, rbuffer.length);
                    datasocket.receive(rPacket);
                    String retstring = new String(rPacket.getData());
                    System.out.println(retstring);
                } catch (IOException e) {
                    System.err.println(e);
                }
            } // while
}      } // end main

    Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)            5
    A connection is set up between the sender and the
     receiver
    Class Socket
      Socket(String host, int port) : creates a stream socket
       and connects it to the specified port number on the host
      InputStream getInputStream() : returns an input stream for
       reading bytes from this socket
      OutputStream getOutputStream() : returns an output
       stream for writing bytes to this socket




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)           6
 Creates a server side socket on the specified
  port
 class ServerSocket
      InetAddress getInetAddress() :
       returns the address to which this socket is
       connected
      Socket accept() : blocking method which
       waits for a connection to be made and accepts it


Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   7
    Maps a name to the host and port number
      Create a server socket
      Listen for incoming connections (accept())




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   8
//NameServer
public class NameServer {
    NameTable table;
    public NameServer() {
        table = new NameTable();
    }
    void handleclient(Socket theClient) {
             BufferedReader din = new BufferedReader
             (new InputStreamReader(theClient.getInputStream()));
             PrintWriter pout = new PrintWriter(theClient.getOutputStream());
             String getline = din.readLine();
             StringTokenizer st = new StringTokenizer(getline);
             String tag = st.nextToken();
             if (tag.equals("search")) {
                           ...

              } else if (tag.equals("insert")) {
                            ...

              }

    }
    public static void main(String[] args) {
        NameServer ns = new NameServer();
        System.out.println("NameServer started:");
            ServerSocket listener = new ServerSocket(Symbols.ServerPort);
            while (true) {
                Socket aClient = listener.accept();
                ns.handleclient(aClient);
                aClient.close();
            }
    }
}



     Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)                  9
//Client for name server
public class Name {
    BufferedReader din;
    PrintStream pout;
    public void getSocket() throws IOException {
        Socket server = new Socket(Symbols.nameServer, Symbols.ServerPort);
        din = new BufferedReader(new InputStreamReader(server.getInputStream()));
        pout = new PrintStream(server.getOutputStream());
    }
    public int insertName(String name, String hname, int portnum){
        getSocket();
        pout.println("insert " + name + " " + hname + " " + portnum);
        pout.flush();
        return Integer.parseInt(din.readLine());
    }
    public PortAddr searchName(String name) throws IOException {
        getSocket();
        pout.println("search " + name);
        pout.flush();
        String result = din.readLine();
        StringTokenizer st = new StringTokenizer(result);
        int portnum = Integer.parseInt(st.nextToken());
        String hname = st.nextToken();
        return new PortAddr(hname, portnum);
    }
    public static void main(String[] args) {
        Name myClient = new Name();
         myClient.insertName("hello1", "birch.ece.utexas.edu", 1000);
            PortAddr pa = myClient.searchName("hello1");
            System.out.println(pa.gethostname() + ":" + pa.getportnum());
      }
}




     Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)                      10
 Methods can be called by another JVM on a
  different host
 Interface is remote if it extends Remote
 Remote object implements a remote
  interface and extends UnicastRemoteObject

 public interface NameService extends Remote {
     public int search(String s) throws RemoteException;
     public int insert(String s, String hostName, int portNumber)
             throws RemoteException;
     public int getPort(int index) throws RemoteException;
     public String getHostName(int index) throws RemoteException;
 }
Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)           11
// A name service implementation
public class NameServiceImpl extends UnicastRemoteObject
        implements NameService {
        . . .

    public NameServiceImpl() throws RemoteException {
    }
    public int search(String s) throws RemoteException {
        . . .
    }
    public int insert(String s, String hostName, int portNumber)
            throws RemoteException {
        . . .

    }
    public int getPort(int index) throws RemoteException {
        return ports[index];
    }
    public String getHostName(int index) throws RemoteException {
        return hosts[index];
    }
    public static void main(String args[]) {
        // create security manager
        System.setSecurityManager(new RMISecurityManager());
       NameServiceImpl obj = new NameServiceImpl();
        Naming.rebind("MyNameServer", obj);
        System.out.println("MyNameServer bound in registry");
       }
}

    Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)       12
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class NameServiceImpl extends UnicastRemoteObject
        implements NameService {
    final int maxSize = 100;
    private String[] names = new String[maxSize];
    private String[] hosts = new String[maxSize];
    private int[] ports = new int[maxSize];
    private int dirsize = 0;
    public NameServiceImpl() throws RemoteException {
    }
    public int search(String s) throws RemoteException {
        for (int i = 0; i < dirsize; i++)
            if (names[i].equals(s)) return i;
        return -1;
    }

Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   13
public int insert(String s, String hostName, int
   portNumber)
             throws RemoteException {
         int oldIndex = search(s); // is it already there
         if ((oldIndex == -1) && (dirsize < maxSize)) {
             names[dirsize] = s;
             hosts[dirsize] = hostName;
             ports[dirsize] = portNumber;
             dirsize++;
             return 1;
         } else
             return 0;
     }
     public int getPort(int index) throws RemoteException
   {
         return ports[index];
     }
Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   14
public String getHostName(int index) throws
    RemoteException {
               return hosts[index];
        }
        public static void main(String args[]) {
               // create security manager
               System.setSecurityManager(new
    RMISecurityManager());
               try {
                        NameServiceImpl obj = new NameServiceImpl();
                        Naming.rebind("MyNameServer", obj);
                        System.out.println("MyNameServer bound in
    registry");
               } catch (Exception e) {
                        System.out.println("NameServiceImpl err: " +
    e.getMessage());
               }
        }
Pemrograman Terdistribusi  Sistem Terdistribusi (IKH331)               15
    Primitive types are passed by value
    Objects (that are not remote)
      They are serialized and then passed by value.
      At the other end the objects are deserialized
      Any references inside the object are also
         serialized
    Remote Objects
      Passed as remote references (stubs)


Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   16
    Obtain a reference for the remote object
    URL for the remote object is specified as
      rmi://host:port/name




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   17
//A RMI client program
import java.rmi.*;
public class NameRmiClient {
    public static void main(String args[]) {
        try {
            NameService r = (NameService)
                   Naming.lookup("rmi://linux02/MyNameServer");
            int i = r.insert("p1", "tick.ece", 2058);
            int j = r.search("p1");
            if (j != -1)
                System.out.println(r.getHostName(j) + ":" +

           r.getPort(j));
             } catch (Exception e) {
                 System.out.println(e);
             }
       }
}

Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)         18
 Vijay Garg, "Concurrent and Distributed
  Programming in Java"
 Source code
  http://users.ece.utexas.edu/~garg/jbk.html
 http://tjerdastangkas.blogspot.com/search/la
  bel/ikh331




Pemrograman Terdistribusi   Sistem Terdistribusi (IKH331)   19
Kamis, 10 November 2011

More Related Content

KEY
Non blocking io with netty
PDF
Lecture6
PPT
Socket Programming
PPTX
分散式系統
PDF
JAVA NIO
PPTX
PPT
Network
DOCX
Winform
Non blocking io with netty
Lecture6
Socket Programming
分散式系統
JAVA NIO
Network
Winform

What's hot (19)

PPTX
Socket.io v.0.8.3
PDF
5. Ввод-вывод, доступ к файловой системе
PPTX
Java nio ( new io )
PPT
Pemrograman Jaringan
PDF
Netty: asynchronous data transfer
PPT
Socket System Calls
PDF
Advanced Sockets Programming
PPTX
#5 (Remote Method Invocation)
PPT
NIO.2, the I/O API for the future
DOCX
Udp socket programming(Florian)
PDF
Active Software Documentation using Soul and IntensiVE
PPT
C# Application program UNIT III
PDF
Application-Specific Models and Pointcuts using a Logic Meta Language
PDF
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
PDF
Network Sockets
PPTX
In kor we Trust
PDF
Advanced Java Practical File
PDF
OSGi Puzzlers
PPTX
Apache Flink Training: DataStream API Part 2 Advanced
Socket.io v.0.8.3
5. Ввод-вывод, доступ к файловой системе
Java nio ( new io )
Pemrograman Jaringan
Netty: asynchronous data transfer
Socket System Calls
Advanced Sockets Programming
#5 (Remote Method Invocation)
NIO.2, the I/O API for the future
Udp socket programming(Florian)
Active Software Documentation using Soul and IntensiVE
C# Application program UNIT III
Application-Specific Models and Pointcuts using a Logic Meta Language
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Network Sockets
In kor we Trust
Advanced Java Practical File
OSGi Puzzlers
Apache Flink Training: DataStream API Part 2 Advanced
Ad

Viewers also liked (20)

PPTX
Pemrosesan pada sistem terdistribusi
DOCX
Sistem terdistribusi
PPTX
Pemrograman sistem teristribusi
PPTX
Sistem terdistribusi (dhaa3)
PPTX
Konsep dasar sistem terdistribusi
PPTX
membuat function dalam mysql
PPTX
Sister pertemuan 1
PPTX
Tiara ramadhani, sitem terdistibusi, final project, 2017
PPTX
3-konsep dasar sistem terdistribusi
PDF
Kuliah 1 pengantar sistem terdistribusi
PPT
message passing
PPT
Chap 4
PDF
PPTX
Pertemuan Dua
PDF
FUNGSI – FUNGSI DALAM MYSQL
PPT
distributed shared memory
PDF
Scientific Applications of The Data Distribution Service
PDF
Platform prototype for ZL Vórtice
PPS
PDF
ikh311-03
Pemrosesan pada sistem terdistribusi
Sistem terdistribusi
Pemrograman sistem teristribusi
Sistem terdistribusi (dhaa3)
Konsep dasar sistem terdistribusi
membuat function dalam mysql
Sister pertemuan 1
Tiara ramadhani, sitem terdistibusi, final project, 2017
3-konsep dasar sistem terdistribusi
Kuliah 1 pengantar sistem terdistribusi
message passing
Chap 4
Pertemuan Dua
FUNGSI – FUNGSI DALAM MYSQL
distributed shared memory
Scientific Applications of The Data Distribution Service
Platform prototype for ZL Vórtice
ikh311-03
Ad

Similar to ikh331-06-distributed-programming (20)

PPT
Chapter 4 slides
PDF
PPT
TCP IP
PPTX
#2 (UDP)
PPT
Java Socket Programming
PDF
IKH331-07-java-rmi
PDF
Laporan multiclient chatting client server
PDF
nw-lab_dns-server.pdf
PPTX
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
PDF
java sockets
DOCX
Lab manual cn-2012-13
PDF
Frequency .java Word frequency counter package frequ.pdf
PDF
DCN Practical
ODP
Jersey Guice AOP
PPTX
Advance Java-Network Programming
PPT
Network programming1
PPTX
Anti patterns
PPTX
CHAPTER - 3 - JAVA NETWORKING.pptx
DOCX
JavaExamples
PPT
Ppt of socket
Chapter 4 slides
TCP IP
#2 (UDP)
Java Socket Programming
IKH331-07-java-rmi
Laporan multiclient chatting client server
nw-lab_dns-server.pdf
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
java sockets
Lab manual cn-2012-13
Frequency .java Word frequency counter package frequ.pdf
DCN Practical
Jersey Guice AOP
Advance Java-Network Programming
Network programming1
Anti patterns
CHAPTER - 3 - JAVA NETWORKING.pptx
JavaExamples
Ppt of socket

More from Anung Ariwibowo (20)

PDF
isd314-06-association-mining
PDF
ikp213-unifikasi
PDF
ikp213-06-horn-clause
PDF
ikp213-01-pendahuluan
PDF
ikd312-05-sqlite
PDF
ikd312-05-kalkulus-relasional
PDF
ikd312-04-aljabar-relasional
PDF
ikd312-03-design
PDF
ikd312-02-three-schema
PDF
ikp213-02-pendahuluan
PDF
ikh311-08
PDF
ikh311-07
PDF
ikh311-06
PDF
ikh311-05
PDF
ikp321-svn
PDF
ikh311-04
PDF
ikp321-05
PDF
imsakiyah-jakarta-1433-09
PDF
ikp321-04
PDF
ikp321-03
isd314-06-association-mining
ikp213-unifikasi
ikp213-06-horn-clause
ikp213-01-pendahuluan
ikd312-05-sqlite
ikd312-05-kalkulus-relasional
ikd312-04-aljabar-relasional
ikd312-03-design
ikd312-02-three-schema
ikp213-02-pendahuluan
ikh311-08
ikh311-07
ikh311-06
ikh311-05
ikp321-svn
ikh311-04
ikp321-05
imsakiyah-jakarta-1433-09
ikp321-04
ikp321-03

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
MYSQL Presentation for SQL database connectivity
20250228 LYD VKU AI Blended-Learning.pptx
Unlocking AI with Model Context Protocol (MCP)
Advanced methodologies resolving dimensionality complications for autism neur...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation_ Review paper, used for researhc scholars
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
A Presentation on Artificial Intelligence
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
“AI and Expert System Decision Support & Business Intelligence Systems”
CIFDAQ's Market Insight: SEC Turns Pro Crypto

ikh331-06-distributed-programming

  • 2. UDP  Low-level, connectionless  No reliability guarantee  TCP  Connection-oriented  Not as efficient as UDP Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 2
  • 3. The sending/receiving point- Class DatagramSocket  void close() : close a datagram socket  int getLocalPort() : returns the port number on which socket is bound  InetAddress getLocalAddress() : returns the local address to which the socket is bound  void receive(DatagramPacket p) : blocks until a datagram is received and the packet’s buffer contains the data received  void send(DatagramPacket p) : sends a datagram packet from this socket Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 3
  • 4. //Datagram Server public class DatagramServer { public static void main(String[] args) { DatagramPacket datapacket, returnpacket; int port = 2018; int len = 1024; try { DatagramSocket datasocket = new DatagramSocket(port); byte[] buf = new byte[len]; datapacket = new DatagramPacket(buf, buf.length); while (true) { try { datasocket.receive(datapacket); returnpacket = new DatagramPacket( datapacket.getData(), datapacket.getLength(), datapacket.getAddress(), datapacket.getPort()); datasocket.send(returnpacket); } catch (IOException e) { System.err.println(e); } } } catch (SocketException se) { System.err.println(se); } } } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 4
  • 5. //Datagram Client public class DatagramClient { public static void main(String[] args) { String hostname; int port = 2018; int len = 1024; DatagramPacket sPacket, rPacket; InetAddress ia = InetAddress.getByName(hostname); DatagramSocket datasocket = new DatagramSocket(); BufferedReader stdinp = new BufferedReader( new InputStreamReader(System.in)); while (true) { String echoline = stdinp.readLine(); if (echoline.equals("done")) break; byte[] buffer = new byte[echoline.length()]; buffer = echoline.getBytes(); sPacket = new DatagramPacket(buffer, buffer.length, ia, port); datasocket.send(sPacket); byte[] rbuffer = new byte[len]; rPacket = new DatagramPacket(rbuffer, rbuffer.length); datasocket.receive(rPacket); String retstring = new String(rPacket.getData()); System.out.println(retstring); } catch (IOException e) { System.err.println(e); } } // while } } // end main Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 5
  • 6. A connection is set up between the sender and the receiver  Class Socket  Socket(String host, int port) : creates a stream socket and connects it to the specified port number on the host  InputStream getInputStream() : returns an input stream for reading bytes from this socket  OutputStream getOutputStream() : returns an output stream for writing bytes to this socket Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 6
  • 7.  Creates a server side socket on the specified port  class ServerSocket  InetAddress getInetAddress() : returns the address to which this socket is connected  Socket accept() : blocking method which waits for a connection to be made and accepts it Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 7
  • 8. Maps a name to the host and port number  Create a server socket  Listen for incoming connections (accept()) Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 8
  • 9. //NameServer public class NameServer { NameTable table; public NameServer() { table = new NameTable(); } void handleclient(Socket theClient) { BufferedReader din = new BufferedReader (new InputStreamReader(theClient.getInputStream())); PrintWriter pout = new PrintWriter(theClient.getOutputStream()); String getline = din.readLine(); StringTokenizer st = new StringTokenizer(getline); String tag = st.nextToken(); if (tag.equals("search")) { ... } else if (tag.equals("insert")) { ... } } public static void main(String[] args) { NameServer ns = new NameServer(); System.out.println("NameServer started:"); ServerSocket listener = new ServerSocket(Symbols.ServerPort); while (true) { Socket aClient = listener.accept(); ns.handleclient(aClient); aClient.close(); } } } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 9
  • 10. //Client for name server public class Name { BufferedReader din; PrintStream pout; public void getSocket() throws IOException { Socket server = new Socket(Symbols.nameServer, Symbols.ServerPort); din = new BufferedReader(new InputStreamReader(server.getInputStream())); pout = new PrintStream(server.getOutputStream()); } public int insertName(String name, String hname, int portnum){ getSocket(); pout.println("insert " + name + " " + hname + " " + portnum); pout.flush(); return Integer.parseInt(din.readLine()); } public PortAddr searchName(String name) throws IOException { getSocket(); pout.println("search " + name); pout.flush(); String result = din.readLine(); StringTokenizer st = new StringTokenizer(result); int portnum = Integer.parseInt(st.nextToken()); String hname = st.nextToken(); return new PortAddr(hname, portnum); } public static void main(String[] args) { Name myClient = new Name(); myClient.insertName("hello1", "birch.ece.utexas.edu", 1000); PortAddr pa = myClient.searchName("hello1"); System.out.println(pa.gethostname() + ":" + pa.getportnum()); } } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 10
  • 11.  Methods can be called by another JVM on a different host  Interface is remote if it extends Remote  Remote object implements a remote interface and extends UnicastRemoteObject public interface NameService extends Remote { public int search(String s) throws RemoteException; public int insert(String s, String hostName, int portNumber) throws RemoteException; public int getPort(int index) throws RemoteException; public String getHostName(int index) throws RemoteException; } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 11
  • 12. // A name service implementation public class NameServiceImpl extends UnicastRemoteObject implements NameService { . . . public NameServiceImpl() throws RemoteException { } public int search(String s) throws RemoteException { . . . } public int insert(String s, String hostName, int portNumber) throws RemoteException { . . . } public int getPort(int index) throws RemoteException { return ports[index]; } public String getHostName(int index) throws RemoteException { return hosts[index]; } public static void main(String args[]) { // create security manager System.setSecurityManager(new RMISecurityManager()); NameServiceImpl obj = new NameServiceImpl(); Naming.rebind("MyNameServer", obj); System.out.println("MyNameServer bound in registry"); } } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 12
  • 13. import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class NameServiceImpl extends UnicastRemoteObject implements NameService { final int maxSize = 100; private String[] names = new String[maxSize]; private String[] hosts = new String[maxSize]; private int[] ports = new int[maxSize]; private int dirsize = 0; public NameServiceImpl() throws RemoteException { } public int search(String s) throws RemoteException { for (int i = 0; i < dirsize; i++) if (names[i].equals(s)) return i; return -1; } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 13
  • 14. public int insert(String s, String hostName, int portNumber) throws RemoteException { int oldIndex = search(s); // is it already there if ((oldIndex == -1) && (dirsize < maxSize)) { names[dirsize] = s; hosts[dirsize] = hostName; ports[dirsize] = portNumber; dirsize++; return 1; } else return 0; } public int getPort(int index) throws RemoteException { return ports[index]; } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 14
  • 15. public String getHostName(int index) throws RemoteException { return hosts[index]; } public static void main(String args[]) { // create security manager System.setSecurityManager(new RMISecurityManager()); try { NameServiceImpl obj = new NameServiceImpl(); Naming.rebind("MyNameServer", obj); System.out.println("MyNameServer bound in registry"); } catch (Exception e) { System.out.println("NameServiceImpl err: " + e.getMessage()); } } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 15
  • 16. Primitive types are passed by value  Objects (that are not remote)  They are serialized and then passed by value.  At the other end the objects are deserialized  Any references inside the object are also serialized  Remote Objects  Passed as remote references (stubs) Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 16
  • 17. Obtain a reference for the remote object  URL for the remote object is specified as  rmi://host:port/name Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 17
  • 18. //A RMI client program import java.rmi.*; public class NameRmiClient { public static void main(String args[]) { try { NameService r = (NameService) Naming.lookup("rmi://linux02/MyNameServer"); int i = r.insert("p1", "tick.ece", 2058); int j = r.search("p1"); if (j != -1) System.out.println(r.getHostName(j) + ":" + r.getPort(j)); } catch (Exception e) { System.out.println(e); } } } Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 18
  • 19.  Vijay Garg, "Concurrent and Distributed Programming in Java"  Source code http://users.ece.utexas.edu/~garg/jbk.html  http://tjerdastangkas.blogspot.com/search/la bel/ikh331 Pemrograman Terdistribusi Sistem Terdistribusi (IKH331) 19