Up Previous Next

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;

public class Server extends UnicastRemoteObject implements ServerExports {
  int index = -1;

  synchronized public int register(ClientExports client) throws RemoteException { 
    clients[++index] = client;
    return index;
  }

  ClientExports clients[] = new ClientExports[100];
  synchronized public void broadcast(Update event) throws RemoteException {
    for (int i = 0; i <= index; i++)
      clients[i].update(event);
  }
  public Server() throws RemoteException {
    System.out.println("Server being initialized... ");
  }
  public static void main(String[] args) {
  
  }
}

import java.rmi.*;

public interface ServerExports extends Remote {
  public int register(ClientExports client) throws RemoteException ;
  public void broadcast(Update event) throws RemoteException ;
}

public class Simulation {
  public static void main(String[] args) throws RemoteException { 
    // on the server's host
    Server server = new Server();

    // on any of the clients' hosts
    ServerExports far = server;

    Client adrian = new Client("Adrian");
    adrian.id = far.register(adrian);
    adrian.server = far;
    adrian.start();

    Client bjorn = new Client("Bjorn");
    bjorn.id = far.register(bjorn);
    bjorn.server = far;
    bjorn.start();

    Client petchel = new Client("Tom");
    petchel.id = far.register(petchel);
    petchel.server = far;
    petchel.start();
  }
}
import java.rmi.*;
import java.rmi.server.*;

public class Client extends Thread implements ClientExports {
  String name;
  int id;
  ServerExports server;
  public Client(String name) { this.name = name; }
  public void update(Update event) throws RemoteException {
    System.out.println(this.name + " receives: ***(" + event + ")*** ");
  }
  public void run() {
    while (true) {
      try { sleep((int)(Math.random() * 6000 + 10000)); }
      catch (Exception e) { }
      server.broadcast(new Update(this.name + " says: Howdy!"));
    }
  }
  public static void main(String[] args) {

  } 
}

import java.rmi.*;

public interface ClientExports extends Remote {
  public void update(Update event) throws RemoteException ;
}

import java.io.*;

public class Update implements Serializable {
  Update(String message) {
    this.message = message;
  }
  String message;
  public String toString() {
    return message;
  }
}
These changes allow the programs to start in a distributed fashion; as one can see, changes are entirely decorative.
Up Previous Next