package RMIexample;

import java.util.*;
import java.rmi.*;
import java.rmi.server.*;

public class Server extends UnicastRemoteObject implements ServerInterface {

  private ArrayList clients = new ArrayList();

	public Server() throws RemoteException {}

	public void connect(String name, ChatObjectInterface c)
	{
	  try{
		System.out.println(name+" entered");
		if (c != null && name != null) {
		  clients.add(c);
		}
	  }catch(Exception e){
		System.out.println("Error While connecting: "+e);
	  }
	}

	public void send(String name, String message)
	{
	  try{
	    int i=0;
	    while(i<clients.size()){
		ChatObjectInterface client = (ChatObjectInterface) clients.get(i);
		client.receive(name,message);
		i++;
	    }
  	  }
	  catch(Exception e){
		System.out.println("Error While sending: "+e);
	  }
	}

	public static void main(String[] args) {
		try {
			Server server = new Server();
			Naming.rebind("RMICHAT", server);
		} catch (Exception e) {
			System.out.println("Error while naming: "+e);

		}
	}
} 