1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
public interface ChatClient extends Remote {
void receive(String s) throws RemoteException;
}
public class ChatClientImpl extends UnicastRemoteObject implements ChatClient, Runnable {
private ChatServer mycs;
public ChatClientImpl(ChatServer cs) throws RemoteException {
mycs = cs;
mycs.register(this);
}
public synchronized void receive(String s) throws RemoteException {
System.out.println("Message :" + s);
}
public void run() {
Scanner in = new Scanner(System.in);
String msg;
while (true) {
try {
msg = in.nextLine();
mycs.broadcast(msg);
} catch (Exception e) {
System.err.println("problem");
}
}
}
public static void main(String[] args) {
String url = "rmi://localhost/ChatServer";
try {
ChatServer cs = (ChatServer) Naming.lookup(url);
new Thread(new ChatClientImpl(cs)).start();
} catch (Exception e) {
System.err.println("Problem");
}
}
}
public interface ChatServer extends Remote {
void register(ChatClient c) throws RemoteException;
void broadcast(String s) throws RemoteException;
}
public class ChatServerImpl extends UnicastRemoteObject implements ChatServer {
private LinkedList <ChatClient> myclients ;
public ChatServerImpl() throws RemoteException {
myclients = new LinkedList();
}
public synchronized void register(ChatClient c) throws RemoteException {
myclients.add(c);
}
public synchronized void broadcast(String s) throws RemoteException {
for (int i = 0; i < myclients.size(); i++) {
myclients.get(i).receive(s);
}
}
public static void main(String[] args) {
try {
Naming.rebind("ChatServer", new ChatServerImpl());
} catch (Exception e) {
System.err.println("Problem");
}
}
} |
Partager