Server
Package Server;import Java.rmi.naming;import Java.rmi.rmisecuritymanager;import java.rmi.registry.LocateRegistry; Import Service.calc;import Serviceimpl.calcimpl;public class server{ //Due to this test we are end users, so throw exceptions directly to the virtual machine public static void Main (string[] args) throws Exception { System.setsecuritymanager (new Rmisecuritymanager ());//Permissions system.setproperty ("Java.rmi.server.hostname", "192.168.1.119"); Specify an extranet IP locateregistry.createregistry (9000); System.setproperty ("Java.security.policy", "/home/ufo/workspace_java/rmiserver/calc.policy"); Calc C = new Calcimpl (); Naming.rebind ("Rmi://192.168.1.119:9000/calc", c); SYSTEM.OUT.PRINTLN ("RMI Server start ...");}
Service
Package Service;import java.rmi.*;p ublic interface Calc extends Remote {public int add (int x,int y) throws RemoteException ;}
Service Impl
Package Serviceimpl;import Java.rmi.remoteexception;import Java.rmi.server.unicastremoteobject;import Service.Calc ;p ublic class Calcimpl extends UnicastRemoteObject implements calc{/** * */private static final long Serialversionuid = 6523564220840187253l;public Calcimpl () throws RemoteException {super ();//TODO auto-generated constructor stub}@ overridepublic int Add (int x, int y) {//TODO auto-generated method StubSystem.out.println ("Add called!"); return x+y;}}
Client
Package Client;import java.rmi.*; Import Java.net.malformedurlexception;import Service.calc;public class Client { //Also for convenience, direct exception throws public static void Main (string[] args) throws Exception { System.setsecuritymanager (new Rmisecuritymanager ()); Try {// here because it is local so omit the address and protocol, if the remote method call in the network, need to write this //Converter C = (Converter) naming.lookup ("rmi:// 192.168.0.13/convert "); Calc C = (Calc) naming.lookup ("Rmi://192.168.1.119:9000/calc"); int RMB = C.add (10,20); SYSTEM.OUT.PRINTLN ("Add Result:" + RMB); } catch (malformedurlexception e) { e.printstacktrace (); } catch (RemoteException e) { e.printstacktrace (); } catch (notboundexception e) { e.printstacktrace ();}} }
Both the client and server sides need to develop class permission files, which are command Java-djava.security.policy=./calc.policy server at startup. Server[client. Client]
Calc.policy
Grant {
Permission java.security.AllPermission;
};
The client also needs a service interface declaration
How to use Java RMI