23. January 2013
von Blackbam
This ultra short tutorial is just a summary of how Java RMI (remote method invocation) works. For explanation please check one of the other tutorials which you will find easily easily your favorite search engine.

1. Write RMI-Server Interface

  • extends package java.rmi.Remote
  • provide all methods to be called remotely
  • each methods must through a remote exception
import java.rmi.*;
 
public interface ServerInterface extends Remote {
     public void method1() throws RemoteException;
     public int method2() throws RemoteException;
     // ...
}

2. Write Server Class

  • implements RMI-Server Interface
  • extends UnicastRemoteObject (at least for simple RMI)
  • Constructor throws java.rmi.RemoteException
  • must be registered at local registry
 
import java.rmi.*;
import java.net.MalformedURLExcpetion;
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
 
public class MyServer extends UnicastRemoteObject implements ServerInterface {
 
  MyServer() throws RemoteException {
    super();
  }
 
  public static void main(String[] args) {

    try {
      LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
    } catch (RemoteException ex) {
      System.out.println(ex.getMessage());
    }
    try {
      Naming.rebind("MyServer", new MyServer());
    } catch (MalformedURLException ex) {
      System.out.println(ex.getMessage());
    }
    catch (RemoteException ex) {
      System.out.println(ex.getMessage());
    }
  }
  // ...
}

3. Write a client

  • get remote reference
  • call remote methods
  • be careful with rmi-specific problems (a more detailed tutorial will explain to you)
 
// any class, ...
// url expects String in url format (e.g. http://127.0.0.1/MyServer for local testing)
 
try {
      ServerInterface server = (ServerInterface) Naming.lookup(url);
      server.method1();
      int calculated_by_server = server.method2();
      // ...
} catch (Exception ex) {

}
  API reference:   Further reading: http://docs.oracle.com/javase/tutorial/rmi/index.html
Share

Dieser Eintrag wurde am 23. January 2013 um 10:10 in der Kategorie Java, Programming veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.


Tags: , , ,

No comments yet

Kommentare abonnieren (RSS) or URL Trackback

Leave a comment:

Current day month ye@r *