Download Remote Method Invocation (rmi)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Dosen Pengasuh Mata Kuliah : Julian Supardi
Sumber slide: Ir. Risanuri Hidayat, M.Sc.
(www.te.ugm.ac.id/~risanuri/jarin/rmiRisanuri.ppt)


Remote Procedure Calls (RPCs)
◦ Memanggil fungsi yang berada di komputer lain
◦ Komunikasi di atas jaringan
◦ Marshal data
◦ Tipe-tipe data terbatas
◦ Cenderung memakai interface definition language (IDL)
Remote Method Invocation (RMI)
◦ Implementasi RPC dengan Java
◦ Meng-handle marshaling data across the network
◦ Transfer Java objects
◦ No IDL is required



Java Remote Method Invocation (RMI) system
memungkinkan object yang running di satu
JVM untuk memanggil suatu metode dar
satu object yang running di JVM yang lain.
RMI memungkinkan komunikasi remote
antar program JAVA
Note: Jika program tersambung ke suatu
program IDL, sebaiknya kita pakai Java IDL
dari pada memakai RMI. (baca sendiri IDL)

Ilustrasi RMI
Local Machine (Client)
Remote Machine (Server)
SampleServer remoteObject;
int s;
…
s = remoteObject.sum(1,2);
1,2
3
System.out.println(s);
public int sum(int a,int b)
{
return a + b;
}




Aplikasi RMI sering terbagi menjadi dua bagian:
server dan client.
Server mempunyai beberapa remote objects,
dan reference-nya, serta menunggu jika client
ingin memanggil remote object tersebut
Client mendapatkan remote refernce untuk satu
atau lebih remote object di dalam server, dan
kemudian memanggil metode di dalamnya.
RMI menyediakan mekanisme sehingga server
dan client dapat berkomunikasi dan tukar
menukar informasi timbal balik. Aplikasi seperti
ini disebut dengan distributed object
application.



Salahsatu keuntungan RMI adalah
kemampuan untuk download bytecodes
(code) dari suatu object's class, jika class tsb
tidak terdefinisikan di VM-nya penerima.
Type-type dan metode-metode object
(class), yang terletak dalam satu VM, dapat
dikirim ke VM yang lain, yang mungkin saja
remote.
Sifat-sifat object yang terkirim ini tidak
berubah sama sekali




Aplikasi terdistribusi dengan Java RMI terdiri atas
interfaces and classes.
Interfaces mendifinisikan methods. Class mengimplement metode yang didefinisikan di dalam interfaces
Objects (perwujudan dari class) yang mempunyai metode
tersebut (yang dapat dipanggil dari jauh) disebut dengan
remote objects.
Suatu object akan menjadi remote jika meng-implement
suatu remote interface, yang mempunyai karakteristik sbb
◦ remote interface meng-extends interface java.rmi.Remote.
◦ Setiap metode interface men-declare java.rmi.RemoteException
di dalam throws clause.


RMI memperlakukan remote object berbeda dengan
yang non-remote object, ketika object tersebut
dikirim ke VM yang lain.
Selain membuat copy object ke VM penerima, RMI
mengirim satu remote stub untuk satu remote
object.
◦ stub ini beraksi sebagai perwakilan lokal, proxy, untuk
remote object tsb, dan untuk pemanggilnya, remote
reference.
◦ Remote reference memanggil metode pada stub lokal,
yang bertanggung jawab untuk memanggil ke remote
object.

Stub (untuk remote object) meng-implements
remote interfaces yang remote object juga mengimplements.


The server must first bind its name to the
registry
The client lookup the server name in the registry
to establish remote references.
The Stub serializing the parameters to skeleton,
the skeleton invoking the remote method and
serializing the result back to the stub.
lookup
Registry
RMI Client
bind
skeleton
call
Stub

RMI Server
return



A client invokes a remote method, the call is first forwarded
to stub.
The stub is responsible for sending the remote call over to
the server-side skeleton
The stub opening a socket to the remote server, marshaling
the object parameters and forwarding the data stream to
the skeleton.
A skeleton contains a method that receives the remote
calls, unmarshals the parameters, and invokes the actual
remote object implementation.
RMI Client
skeleton
call
Stub

RMI Server
return
Ada beberapa langkah untuk membuat aplikasi
terdistribusi dengan RMI
1. Buat satu (atau lebih) Remote Interface
2. Buat Class di server (remote object) yang mengimplement Remote Interface tersebut
3. Buat program di client yang memanggil remote object
tersebut
4. Kompilasi source dan generate stub dan skeleton
5. Start RMI Registry
6. Start (Run) Server
7. Start (Run) Client


To create an RMI application, the first step is the
defining of a remote interface between the client
and server objects.
remote interfaces: menspesifikasikan metode yang dapat
dipanggil oleh client.
/* SampleServer.java */
import java.rmi.*;
public interface SampleServer extends Remote
{
public int sum(int a,int b) throws RemoteException;
}







Remote objects harus meng-implement satu atau lebih remote
interfaces. Remote object class bisa saja meng-implement
interface yang lain (baik lokal ataupun remote) dan metode yang
lain (yang hanya lokal)
The server is a simple unicast remote server.
Create server by extending
java.rmi.server.UnicastRemoteObject.
The server uses the RMISecurityManager to protect its resources
while engaging in remote communication.
The server must bind its name to the registry, the client will look
up the server name.
Use java.rmi.Naming class to bind the server name to registry.
In this example the name call “SAMPLE-SERVER”.
In the main method of your server object, the RMI security
manager is created and installed.
/* SampleServerImpl.java */
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class SampleServerImpl extends UnicastRemoteObject
implements SampleServer {
SampleServerImpl() throws RemoteException
{
super();
}
public int sum(int a,int b) throws RemoteException {
return a + b;
}
public static void main(String args[]) {
try {
System.setSecurityManager(new RMISecurityManager());
//set the security manager
//create a local instance of the object
SampleServerImpl Server = new SampleServerImpl();
//put the local instance in the registry
Naming.rebind("SAMPLE-SERVER" , Server);
System.out.println("Server waiting.....");
}
catch (java.net.MalformedURLException me)
{
System.out.println("Malformed URL: " + me.toString());
}
catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString());
}
}
}





In order for the client object to invoke methods on the
server, it must first look up the name of server in the
registry. You use the java.rmi.Naming class to lookup the
server name.
The server name is specified as URL in the from
(
rmi://host:port/name )
Default RMI port is 1099.
The name specified in the URL must exactly match the
name that the server has bound to the registry. In this
example, the name is “SAMPLE-SERVER”
The remote method invocation is programmed using the
remote interface name (remoteObject) as prefix and the
remote method name (sum) as suffix.
import java.rmi.*;
import java.rmi.server.*;
public class SampleClient {
public static void main(String[] args)
{
// set the security manager for the client
System.setSecurityManager(new RMISecurityManager());
//get the remote object from the registry
try {
System.out.println("Security Manager loaded");
String url = "//localhost/SAMPLE-SERVER";
SampleServer remoteObject = (SampleServer)Naming.lookup(url);
System.out.println("Got remote object");
System.out.println(" 1 + 2 = " + remoteObject.sum(1,2) );
}
catch (RemoteException exc) {
System.out.println("Error in lookup: " + exc.toString()); }
catch (java.net.MalformedURLException exc) {
System.out.println("Malformed URL: " + exc.toString());
}
catch (java.rmi.NotBoundException exc) {
System.out.println("NotBound: " + exc.toString());
}
}
}


Pertama, gunakan javac compiler untuk
meng-kompile source files, yang di sana
terdapat implementasi remote interfaces,
server class, dan client classes.
Kedua, gunakan rmic compiler untuk
membuat stubs untuk remote objects.
RMI menggunakan stub remote object
sebagai proxy pada clients, sehingga
client dapat berkomunikasi dengan
remote object tertentu.


Assume the program compile and executing at
elpis on ~/rmi
Once the interface is completed, you need to
generate stubs and skeleton code. The RMI
system provides an RMI compiler (rmic) that
takes your generated interface class and
procedures stub code on its self.
elpis:~/rmi>
elpis:~/rmi>
elpis:~/rmi>
elpis:~/rmi>
set CLASSPATH=”~/rmi”
javac SampleServer.java
javac SampleServerImpl.java
rmic SampleServerImpl
elpis:~/rmi> javac SampleClient.java


The RMI applications need install to Registry.
And the Registry must start manual by call
rmiregisty.
The rmiregistry us uses port 1099 by default.
You can also bind rmiregistry to a different port
by indicating the new port number as :
rmiregistry <new port>
elpis:~/rmi> rmiregistry

Remark: On Windows, you have to type in from
the command line:
> start rmiregistry


Once the Registry is started, the server can be
started and will be able to store itself in the
Registry.
Because of the grained security model in Java
2.0, you must setup a security policy for RMI by
set java.security.policy to the file
policy.all
elpis:~/rmi> java –Djava.security.policy=policy.all
SampleServerImpl
elpis:~/rmi> java –Djava.security.policy=policy.all
SampleClient

In Java 2, the java application must first obtain information
regarding its privileges. It can obtain the security policy through
a policy file. In above example, we allow Java code to have all
permissions, the contains of the policy file policy.all is:
grant {
permission java.security.AllPermission;
};

Now, we given an example for assigning resource permissions:
grant {
permission java.io.filePermission “/tmp/*”, “read”,
“write”;
permission java.net.SocketPermission
“somehost.somedomain.com:999”,”connect”;
permission java.net.SocketPermission “*:102465535”,”connect,request”;
permission java.net.SocketPermission “*:80”,”connect”;
};
1. allow the Java code to read/write any files only
under
the
/tmp
directory,
includes
any
subdirectories
2.
allow all java classes to establish a network
connection
with
the
host
“somehost.somedomain.com” on port 999
3.
allows classes to connection to or accept
connections on unprivileged ports greater than 1024
, on any host
4.
allows all classes to connect to the HTTP port
80 on any host.

You can obtain complete details by following links:
http://java.sun.com/products//jdk/1.2/docs/guide/security/spec/se
curity-spec.doc3.html
RMI Tutorial
Dengan JBUILDER
Risanuri Hidayat, Ir., M.Sc.
Pendahuluan
●
●
●
●
Tutorial ini memberikan petunjuk
membuat aplikasi RMI sederhana
dengan JBUILDER 5.0
Client mempunyai metode yang
dikerjakan Server
Server menerima panggilan, dan
mengerjakan metode tersebut, hasilnya
dikirim kembali ke client
Aplikasi sederhana ini, client meminta
server menampilkan tulisan “Hallo
Sayang” ke client
File
●
Ada tiga file dalam aplikasi ini
–
–
–
●
RMI02_Iface.java - remote interface
Server_rmi.java - remote object yang
berada di server yang meng-implement
Interface RMI02_Iface
Client_rmi.java – client yang memanggil
metode remote, sayHello
Ada tambahan 1 file untuk alasan set up
security
–
rmi.policy
Remote Interface
package rmi02;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RMI02_iface extends Remote {
String sayHello() throws RemoteException;
}
Server_rmi
package rmi02;
public static void main(String args[]) {
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
// Create and install a security manager
if (System.getSecurityManager() == null) {
System.setSecurityManager(new
RMISecurityManager());
}
try {
Server_rmi obj = new Server_rmi();
// Bind this object instance to the name
// "HelloServer"
Naming.rebind("//localhost/HelloServer",
obj);
System.out.println("HelloServer bound in
registry");
} catch (Exception e) {
System.out.println("HelloImpl err: " +
e.getMessage());
e.printStackTrace();
}
}
}
public class Server_rmi extends
UnicastRemoteObject implements
RMI02_iface {
public Server_rmi() throws RemoteException
{
super();
}
public String sayHello() {
return "Hallo Sayang....";
}
Client_rmi
package rmi02;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class Client_rmi {
public Client_rmi() {
}
public static void main(String[] args) {
String message = "ihik....";
//"obj" is the identifier that we'll use to refer
//to the remote object that implements the
// "Hello"
//interface
RMI02_iface rmi_obj = null;
try {
rmi_obj =
(RMI02_iface)Naming.lookup("//localhost/
HelloServer");
message = rmi_obj.sayHello();
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println(message);
}
}
Compile source
●
●
●
To compile the source files, run the javac command as
follows: javac -d $HOME/public_html/myclasses
Hello.java HelloImpl.java HelloApplet.java
Use rmic to generate skeletons and/or stubs rmic d $HOME/public_html/myclasses examples.hello.Hell
oImpl
The "-d" option indicates the root directory in which to
place the compiled stub and skeleton class files. So
the preceding command creates the following files in
the directory
$HOME/public_html/myclasses/examples/hello:
–
–
HelloImpl_Stub.class
HelloImpl_Skel.class
Compile di JBUILDER
●
●
●
●
●
Right-click HelloImpl.java in the project pane.
Select Properties from the context menu.
Choose the Build page. The Properties dialog box is
displayed.
Check the Generate RMI Stub/Skeleton field on the
RMI/JNI tab of the Build page.
Enter -v1.2 in the Options field and Click OK.
–
●
●
(If you do not enter -v1.2 in the Options field, you will see
deprecation warnings during compilation.)
Click OK to close the dialog box.
Right-click HelloImpl.java and choose Make. The file is
compiled with the RMI compiler, rmic.
Compile di JBUILDER
●
●
●
●
●
●
Memilih RunTime
Configuration
di
JBUILDER
Choose Run|Configurations. The Runtime
Configurations dialog box is displayed.
Click New. On the Application page of the Runtime
Properties dialog box, enter Hello World Server in the
Configuration Name field.
Click the ellipsis button next to the Main class field.
The Select Main Class For Project dialog box is
displayed.
Expand the hello package and choose HelloImpl.
Click OK.
In the VM parameters field of the Runtime Properties
dialog box, enter parameters similar to the following
using your own project directory:
-Djava.rmi.server.codebase=file:d:\myjava\rmi02\ Djava.security.policy= file:d:\myjava\rmi02\rmi02.policy
RunTime Configuration
Start RMI registry
●
●
Click the down arrow next to the Run
button on the JBuilder toolbar. Choose
Hello World Server.
By default, the registry runs on port
1099. To start the registry on a different
port, specify the port number from the
command line. For example, to start the
registry on port 2001 on a Microsoft
Windows NT system: start rmiregistry
2001
Run Server
●
java Djava.rmi.server.codebase=http://myhos
t/~myusrname/myclasses/ Djava.security.policy=$HOME/mysrc/poli
cy examples.hello.HelloImpl
Run Server
●
The output should look like this:
HelloServer bound in registry
rmi02.policy
grant {
// Allow everything for now
permission java.net.SocketPermission
"*:1024-65535", "accept, connect, listen";
};
Menulis file policy di
JBUILDER
●
●
●
Right-click the project file Hello.jpx.
Choose Add Files/Packages.
In the Add Files Or Packages To Project
dialog box, make sure the root of the
project (jbproject/Hello) is selected.
–
●
(Click the Project button to quickly move to
this directory.)
Enter rmi.policy in the File Name field.
Run Client
Hallo Sayang....
Catatan
●
●
Aplikasi RMI di JBUILDER tidak stabil
Sekali melakukan kesalahan, harus
membuat project baru