import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class ChatServerImpl extends UnicastRemoteObject implements ChatServer { private List users = new LinkedList (); public synchronized void send (String name, String text) throws RemoteException { sendToAll (name + ": " + text); } public synchronized void disconnect (String name) throws RemoteException { users.remove(name); sendToAll ("<<" + name + " leaves the chat>>"); } public synchronized void connect (String name, ChatClient client) throws RemoteException { users.add (new User (name, client)); sendToAll ("<<" + name + " enters the chat>>"); } public ChatServerImpl () throws RemoteException { super (); } private void sendToAll (String msg) { Iterator iter = users.iterator (); while (iter.hasNext ()) { User user = (User) iter.next (); try { user.getClient ().send(msg); } catch (RemoteException e) { users.remove (user.getName()); } } } public static void main (String[] args) { try { ChatServerImpl server = new ChatServerImpl (); Naming.rebind ("//localhost:1099/ChatServer", server); System.out.println ("Ready for connections..."); } catch (Exception e) { e.printStackTrace(); } } private static class User { private String name; private ChatClient client; public User (String n, ChatClient c) { name = n; client = c; } public String getName () { return name; } public ChatClient getClient () { return client; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof String) return name.equals (obj); if (! (obj instanceof User)) return false; return name.equals (((User) obj).name); } } }