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 static class ChatMsg { private int id; private String msg; public ChatMsg (int i, String m) { id = i; msg = m; } public int getId () { return id; } public String getMsg () { return msg; } public String toString () { return "" + id + "..." + msg; } } private List msgs = new LinkedList (); private int nextId = 0; public synchronized void send (String name, String text) throws RemoteException { msgs.add (new ChatMsg (nextId++, name + ": " + text)); } public synchronized String get (int id) throws RemoteException { Iterator iter = msgs.iterator (); while (iter.hasNext ()) { ChatMsg cm = (ChatMsg) iter.next (); if (cm.id == id) return cm.msg; } return null; } public synchronized void disconnect (String name) throws RemoteException { msgs.add (new ChatMsg (nextId++, "<<" + name + " leaves the chat>>")); } public synchronized void connect (String name) throws RemoteException { msgs.add (new ChatMsg (nextId++, "<<" + name + " enters the chat>>")); } public ChatServerImpl () throws RemoteException { super (); } 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(); } } }