RMI is an RPC framework in the Java language, this article gives the following basic examples:
1. Implement the interface:
Public Interface extends Remote { publicint Add (intintthrows java.rmi.RemoteException;}
2, the server to implement the interface:
Public classCalcimplextendsUnicastRemoteObjectImplementsIcalc {protectedCalcimpl ()throwsRemoteException {Super(); } @Override Public intAddintPARAM1,intparam2) { returnParam1 +param2; } Public Static voidMain (string[] args) {Icalc calc; Try { //The following code mainly solves the connect confused problemSystem.setproperty ("Java.rmi.server.hostname", "192.168.0.16"); Calc=NewCalcimpl (); Locateregistry.createregistry (1011); Java.rmi.Naming.rebind ("Rmi://192.168.0.16:1011/calc", Calc); } Catch(RemoteException e) {e.printstacktrace (); } Catch(malformedurlexception e) {e.printstacktrace (); } }}
3. Define the test client:
Public class Client { publicstaticvoid main (string[] args) { Icalc calc; Try { = (icalc) naming.lookup ("Rmi://192.168.0.16:1011/calc"); System.out.println (Calc.add (2,3)); Catch (Malformedurlexception | RemoteException | notboundexception e) { e.printstacktrace (); }}}
4. Test execution sequence:
1, server-side compilation Javac Calcimpl
2, create pile file rmic Calcimpl, the directory will be added calcimpl_stub;
3, the implementation of Rmiregister, registration of the procedure;
4. Start the service Java Calcimpl in a new window;
5, copy the calcimpl_stub to the client, execute Java client, the client prints the budget result
JAVA RMI Example