RMI: Zdalny licznik

Interfejs

import java.rmi.Remote;
import java.rmi.RemoteException;
 
 
public interface Count extends Remote{
    int getNext() throws RemoteException;
}

Implementacja serwera

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
 
public class Server extends UnicastRemoteObject implements Count {
    public static int value = 0;
 
    public Server() throws RemoteException {
        super();
    }
 
    public synchronized int getNext() {
           int v = value + 1;
           try {
              Thread.sleep(1000);
           }
           catch(Exception e){};
           value = v;
           return value;
        }
 
    public static void main(String args[]) {
        try {
            Server obj = new Server();
            Registry r = LocateRegistry.createRegistry(6002);
            r.rebind("Server", obj);
 
        } catch (Exception e) {
            System.err.println("Błąd" + e);
        }
    }
 
}

Przykład programu klienta

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
 
public class Client {
    Count obj = null;
 
    public int getNext() {
        try {
            obj = (Count) Naming.lookup("//localhost:6002/Server");
            return obj.getNext();
        } catch (Exception e) {
            System.err.println("Błąd: " + e);
            e.printStackTrace();
        }
        return 0;
    }
 
    public static void main(String args[]) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
 
        Client c1 = new Client();
        System.out.println(c1.getNext());
    }
 
}
rmi/licznik.txt · ostatnio zmienione: 2012/11/14 08:19 przez inf89753
 
Wszystkie treści w tym wiki, którym nie przyporządkowano licencji, podlegają licencji: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki