Bài giảng Lập trình mạng 2 - Java remote method invocation - Nguyễn Xuân Vinh

Tóm tắt Bài giảng Lập trình mạng 2 - Java remote method invocation - Nguyễn Xuân Vinh: ...of this class can be accessed just like any other objectOn other computers, the remote object can be accessed via object handlesA Serializable class is one whose instances can be marshaled (turned into a linear sequence of bits)Serializable objects can be transmitted from one computer to anotherIt p...n’t safe for the client to use somebody else’s code on some random serverSystem.setSecurityManager(new RMISecurityManager());The security policy of RMISecurityManager is the same as that of the default SecurityManagerYour client program should use a more conservative security manager than the defaul...ws RemoteException { return “Hello “ + name + “. ” + message; } }19HelloServer: binding RMI remote objectimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.RemoteException;public class HelloServer { public static void main(String[] args) { try { HelloInterface hello = new ...

ppt26 trang | Chia sẻ: havih72 | Lượt xem: 273 | Lượt tải: 0download
Nội dung tài liệu Bài giảng Lập trình mạng 2 - Java remote method invocation - Nguyễn Xuân Vinh, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
JavaRemote Method InvocationPresenter: Nguyễn Xuân VinhInformation Technology FacultyNong Lam University“The network is the computer”Consider the following program organization:SomeClassAnotherClassmethod callreturned objectcomputer 1computer 2If the network is the computer, we ought to be able to put the two classes on different computersParameter marshallingCalling the remote getDescription methodRMI and other technologiesCORBA (Common Object Request Broker Architecture) was used for a long timeCORBA supports object transmission between virtually any languagesObjects have to be described in IDL (Interface Definition Language), which looks a lot like C++ data definitionsCORBA is complex and flakyCORBA has fallen out of favorMicrosoft supported CORBA, then COM, now .NETRMI is purely Java-specificJava to Java communications onlyAs a result, RMI is much simpler than CORBAWhat is needed for RMIJava makes RMI (Remote Method Invocation) fairly easy, but there are some extra stepsTo send a message to a remote “server object,”The “client object” has to find the objectDo this by looking it up in a registryThe client object then has to marshal the parameters (prepare them for transmission)Java requires Serializable parametersThe server object has to unmarshal its parameters, do its computation, and marshal its responseThe client object has to unmarshal the responseMuch of this is done for you by special softwareTerminologyA remote object is an object on another computerThe client object is the object making the request (sending a message to the other object)The server object is the object receiving the requestAs usual, “client” and “server” can easily trade roles (each can make requests of the other)The rmiregistry is a special server that looks up objects by nameHopefully, the name is unique!rmic is a special compiler for creating stub (client) and skeleton (server) classes8ProcessesFor RMI, you need to be running three processesThe ClientThe ServerThe Object Registry, rmiregistry, which is like a DNS service for objectsYou also need TCP/IP active9InterfacesInterfaces define behaviorClasses define implementationTherefore,In order to use a remote object, the client must know its behavior (interface), but does not need to know its implementation (class)In order to provide an object, the server must know both its interface (behavior) and its class (implementation)In short,The interface must be available to both client and serverThe class of any transmitted object must be on both client and serverThe class whose method is being used should only be on the server10ClassesA Remote class is one whose instances can be accessed remotelyOn the computer where it is defined, instances of this class can be accessed just like any other objectOn other computers, the remote object can be accessed via object handlesA Serializable class is one whose instances can be marshaled (turned into a linear sequence of bits)Serializable objects can be transmitted from one computer to anotherIt probably isn’t a good idea for an object to be both remote and serializable11Conditions for serializabilityIf an object is to be serialized:The class must be declared as publicThe class must implement SerializableHowever, Serializable does not declare any methodsThe class must have a no-argument constructorAll fields of the class must be serializable: either primitive types or Serializable objectsException: Fields marked transient will be ignored during serialization12Remote interfaces and classA Remote class has two parts: The interface (used by both client and server):Must be public Must extend the interface java.rmi.RemoteEvery method in the interface must declare that it throws java.rmi.RemoteException (other exceptions may also be thrown)The class itself (used only by the server):Must implement the Remote interface Should extend java.rmi.server.UnicastRemoteObjectMay have locally accessible methods that are not in its Remote interface13Remote vs. SerializableA Remote object lives on another computer (such as the Server)You can send messages to a Remote object and get responses back from the objectAll you need to know about the Remote object is its interfaceRemote objects don’t pose much of a security issueYou can transmit a copy of a Serializable object between computersThe receiving object needs to know how the object is implemented; it needs the class as well as the interfaceThere is a way to transmit the class definitionAccepting classes does pose a security issue14SecurityIt isn’t safe for the client to use somebody else’s code on some random serverSystem.setSecurityManager(new RMISecurityManager());The security policy of RMISecurityManager is the same as that of the default SecurityManagerYour client program should use a more conservative security manager than the defaultMost discussions of RMI assume you should do this on both the client and the serverUnless your server also acts as a client, it isn’t really necessary on the server15The server classThe class that defines the server object should extend UnicastRemoteObjectThis makes a connection with exactly one other computerIf you must extend some other class, you can use exportObject() insteadSun does not provide a MulticastRemoteObject classThe server class needs to register its server object:String url = "rmi://" + host + ":" + port + "/" + objectName;The default port is 1099Naming.rebind(url, object);Every remotely available method must throw a RemoteException (because connections can fail)Every remotely available method should be synchronizedHelloServerExample: HelloWorldHelloInterfaceHelloImplJava.rmi.RemoteextendsimplementsUnicastRemoteObjectHelloClientRMI Registry(1) bind()(2) lookup()HelloInterface(3) sayHello(“Vinh”)extends17HelloInterface: interfaceimport java.rmi.Remote;import java.rmi.RemoteException;public interface HelloInterface extends Remote {	public String sayHello(String name)throws RemoteException;}18HelloImpl: class implement HelloInterfaceimport java.rmi.*;import java.rmi.server.*;public class HelloImpl extends UnicastRemoteObject implements HelloInterface {	private String message; // Strings are serializable	public HelloImpl() throws RemoteException {	super();	}	public Hello (String msg) throws RemoteException {	message = msg;	}	public String sayHello(String name) throws RemoteException {	return “Hello “ + name + “. ” + message;	}}19HelloServer: binding RMI remote objectimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.RemoteException;public class HelloServer {	public static void main(String[] args) { 	try {	HelloInterface hello = new HelloImpl(“Welcome to HelloWorld RMI”);	try {	Naming.rebind("rmi://localhost:1234/hello", hello);	System.out.println("Hello Server is ready.");	} catch (MalformedURLException e) {	e.printStackTrace();	}	} catch (RemoteException e) {	System.out.println("Hello Server failed: " + e);	}	}}Registry reg = LocateRegistry.createRegistry(1234)reg.rebind("rmi://localhost:1234/hello", hello)20HelloClient: lookup and process RMI objectpublic class HelloClient {	public static void main (String[] args) {	HelloInterface hello;	String name = "rmi://localhost:1234/hello";	try {	hello = (HelloInterface) Naming.lookup(name);	System.out.println(hello.sayHello(“Nguyen Xuan Vinh”));	} catch (Exception e) {	System.out.println("HelloClient exception: " + e);	}	}}Registry reg = LocateRegistry.createRegistry(1234)reg.rebind("rmi://localhost:1234/hello", hello)21rmicThe class that implements the remote object should be compiled as usualThen, it should be compiled with rmic:rmic HelloImplThis will generate files HelloImpl_Stub.class and HelloImpl_Skel.classThese classes do the actual communicationThe “Stub” class must be copied to the client areaThe “Skel” was needed in SDK 1.1 but is no longer necessary22Trying RMIIn three different terminal windows:Run the registry program:rmiregistryRun the server program:java HelloServerRun the client program:java HelloClientIf all goes well, you should get the message: Hello Nguyen Xuan Vinh! Welcome to HelloWorld RMI!Example by CLICompile all *.java to *.classjavac *.javaCompile stub and skeleton* (*:used in JDK1.1)rmic HelloImplStart RMI Registrystart rmiregistryStart serverjava -Djava.security.policy=server.policy HelloServerRun client applicationjava HelloClientgrant { permission java.net.SocketPermission "127.0.0.1:*", "connect,resolve"; permission java.net.SocketPermission "127.0.0.1:*", "accept";};server.policy24SummaryStart the registry server, rmiregistryStart the object serverThe object server registers an object, with a name, with the registry serverStart the clientThe client looks up the object in the registry serverThe client makes a requestThe request actually goes to the Stub classThe Stub classes on client and server talk to each otherThe client’s Stub class returns the result25ReferencesTrail: RMI by Ann Wollrath and Jim Waldo Fundamentals of RMI Short Courseby jGuru rmi/RMI.htmlJava RMI Tutorial by Ken Baclawskirmi_tut.htmlỎI ĐÁP

File đính kèm:

  • pptbai_giang_lap_trinh_mang_2_java_remote_method_invocation_ngu.ppt