java/ch/wlkl/javaExamples/ExRmi.java

package ch.wlkl.javaExamples;

import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.registry.*;

/**
 * @author wake
 * 
 * To change this generated comment edit the template variable "typecomment":
 * Window>Preferences>Java>Templates. To enable and disable the creation of type
 * comments go to Window>Preferences>Java>Code Generation.
 */
public class ExRmi implements Remote, Serializable {
    static final int port = 2345;

    String name;

    static Registry reg = null;

    ExRmi(String name) {
        this.name = name + "{" + hashCode() + "}";
    }

    public String toString() {
        return name;
    }

    public static void createRegistry() {
        try {
            LocateRegistry.createRegistry(port);
            System.out.println("createRegistry ok");
        } catch (Exception e) {
            System.out.println("createRegistry failed " + e);
            System.exit(1);
        }
    }

    public static void getRegistry() {
        try {
            reg = LocateRegistry.getRegistry("localhost", port);
            System.out.println("getRegistry " + reg + " cla " + reg.getClass());
        } catch (Exception e) {
            System.out.println("getRegistry failed " + e);
            System.exit(1);
        }
    }

    public void bind(String name) {
        try {
            reg.bind(name, this);
            System.out.println("bind(" + name + ", " + this + ")");
        } catch (Exception e) {
            System.out.println("bind failed " + e);
            System.exit(1);
        }
    }

    public static void server() {
        createRegistry();
        getRegistry();
        (new ExRmi("erstens")).bind("eins");
        (new ExRmi("zweitens")).bind("zwei");
        try {
            Thread.sleep(10000);
        } catch (Exception e) {
        }
        ;
        System.out.println("after sleep ");
    }

    public static void client() {
        getRegistry();
        Object o;
        try {
            Object x[] = reg.list();
            System.out.println("reg.list() " + x[0] + ", " + x[1]);
            o = reg.lookup("eins");
            System.out.println("lookup erstens " + o);
        } catch (Exception e) {
            System.out.println("lookup erstens ex " + e);
        }
    }

    public static void main(String[] args) {
        if (args.length > 0 && args[0].equals("s"))
            server();
        else
            client();
    }
}